I need to create a list of input boxes based on a array element. However when using x-for for looping and x-model for binding the elements any changes to the input boxes are not transmitted back to the original array.
<div x-data="{items: ['apples','pears']}">
<h3>List of items:</h3>
<template x-for="item in items">
<div>
<input class="text" x-model="item"></input>
</div>
</template>
<br>
<button @click="items.push('')">+</button>
<br>
<span x-text="items"></span>
</div>
How do I fix this to achieve 2-way data binding so that any changes to the input boxes also updates the items array.
This should work:
<div x-data="{items: ['apples','pears']}">
<h3>List of items:</h3>
<template x-for="(item, i) in items">
<div>
<input class="text" x-model="items[i]">
</div>
</template>
<br>
<button @click="items.push('')">+</button>
<br>
<span x-text="items"></span>
</div>