In AlpineJS, is it possible to create x-model tags which bind to objects in an array?

393 Views Asked by At

I have an AlpineJS page which uses something like the following in its x-data:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    <script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/cdn.min.js"></script>
</head>
<body>
    <div x-data="alpineObject()">
        <template x-for="(item, index) in data">
            <div>
                <input type="text" x-bind:id="`name_${index}`" x-bind:name="`name_${index}`" x-bind:x-model="`data[${index}].name`">
            </div>
        </template>
    </div>
    <script>
        function alpineObject() {
            return {
                data: [
                    {
                        name: 'first'
                    },
                    {
                        name: 'second'
                    },
                    {
                        name: 'third'
                    }
                ],
            }
        }
    </script>
</body>
</html>

How can I connect these properties to HTML elements?

I thought using x-bind on x-model would work, but it doesn't (I just get three empty text boxes).

Is there any way to create dynamic x-model tags which work?

1

There are 1 best solutions below

0
Pippo On BEST ANSWER

x-model doesn't need x-bind and must receive a reference to a variable:

<input type="text" x-bind:id="`name_${index}`" x-bind:name="`name_${index}`" x-model="data[index].name">