How to set x-model and name of Input field inside x-for in alpine js?

Viewed 2217

I am getting an issue saving the data with alpine js. I have a form inside a for loop. but, i am unable to set the index for x-model and name of form inputs.

HTML:

<template x-for="(price, index) in prices">
    <tr data-id="price.id">
        <td class="text-right">
            <input type="text" class="form-control" x-bind:name="record.items[${index}].batch" x-model="record.items[${index}].batch">
        </td>
    </tr>
</template>

Javscript

record: {
    items: [],
}

I got this error. Uncaught ReferenceError: index is not defined.

How to resolve this?

1 Answers

I created a CodePen illustrating how you can use the index inside an x-for loop and reference items.

The usage of ${index} in your code seems wrong to me. You should be able to use it just like [index]:

<div x-data="{ prices: myPrices, items: record.items }">
      <template x-for="(price, index) in prices">
        <div>
            <span x-text="price.id"></span>
            <input type="text" x-bind:name="items[index]" x-bind:placeholder="items[index]">
        </div>
      </template>
</div>

Please see the full CodePen for all details.

Related