简体   繁体   English

使用 AlpineJS 在循环中动态设置输入字段的名称属性

[英]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">

See the fixed Codepen查看固定的Codepen

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM