问题
I'd like to set the name
attribute of hidden input fields in a loop with AlpineJS. I've tried x-bind:name
but that doesn't work.
I think this doesn't work because of the x-model
in how todos are added:
<input x-model="todoText" type="text">
<button x-on:click.prevent="addTodo('new', todoText)">
Add
</button>
How can I make the below work so that the index key in the todos
array is set to the todoSingle.id
value?
<template x-for="todoSingle in todoArray" :key="todoSingle.id">
<input type="hidden" name="todos[todoSingle.id][id]" x-model="todoSingle.id">
<input type="hidden" name="todos[todoSingle.id][type]" x-model="todoSingle.type">
<input type="hidden" name="todos[todoSingle.id][description]" x-model="todoSingle.description">
</template>
Update
Codepen here. If you add a todo, then go back to the input field and type, you'll see that on every keyup the same todo is added.
回答1:
You need to use x-bind:name
with a template string:
<input type="hidden" x-bind:name="`todos[${todoSingle.id}][id]`" x-model="todoSingle.id">
<input type="hidden" x-bind:name="`todos[${todoSingle.id}][type]`" x-model="todoSingle.type">
<input type="hidden" x-bind:name="`todos[${todoSingle.id}][description]`" x-model="todoSingle.description">
See the fixed Codepen
来源:https://stackoverflow.com/questions/63574576/dynamically-set-name-attribute-of-input-field-in-loop-with-alpinejs