Problem:
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/alpinejs@3.x.x/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?
Solution:
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">