[英]Dynamically set name attribute of input field in loop with AlpineJS
I'd like to set the name
attribute of hidden input fields in a loop with AlpineJS.我想使用 AlpineJS 在循环中设置隐藏输入字段的
name
属性。 I've tried x-bind:name
but that doesn't work.我试过
x-bind:name
但这不起作用。
I think this doesn't work because of the x-model
in how todos are added:我认为这不起作用,因为在如何添加 todos 中使用了
x-model
:
<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?我怎样才能使下面的工作,以便
todos
数组中的索引键设置为todoSingle.id
值?
<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.
如果添加待办事项,然后返回输入字段并键入,您将看到在每个键上都添加了相同的待办事项。
You need to use x-bind:name
with a template string:您需要将
x-bind:name
与模板字符串一起使用:
<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">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.