Dynamically set name attribute of input field in loop with AlpineJS

馋奶兔 提交于 2021-01-29 06:44:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!