eskimo
eskimo

Reputation: 2625

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. 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.

Upvotes: 5

Views: 6028

Answers (1)

Hugo
Hugo

Reputation: 3888

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

Upvotes: 8

Related Questions