5

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 Answer 1

8

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

Sign up to request clarification or add additional context in comments.

6 Comments

As indicated in the original question x-bind:name doesn't work. What happens is that on every keyup in the input field the todo is added. I've added the input field and the button that adds the todo in my question.
I also get Can't find variable todoSingle and Can't find variable todos
Do you have this running in a codepen? Or the full component code
I'll create one, just a few minutes
Answer updated and have forked the codepen to a working state codepen.io/hugodf/pen/xxVqOeb
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.