Experimenter
Experimenter

Reputation: 3

How do I create a two way binding list of elements consisting of input boxes using AlpineJs

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.

Upvotes: 0

Views: 280

Answers (1)

TUPKAP
TUPKAP

Reputation: 5309

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>

Upvotes: 1

Related Questions