Skip to content
Advertisement

How to dynamically add IDs in checkboxes with vue?

Edit: Similar but slightly different question can be found here: Vue.js : How to set a unique ID for each component instance?

I’m trying to create a table so that someone can check the people they want to add to a group. So far I’ve managed to retrieve them from the DB with PHP and display them with vue in HTML. Now I would like to assign each checkbox ID with the email of the student, so i can send the checked students back to PHP later. There may be (a lot) better ways to do this, but I’m very new to this.

This is my current output: My Output

My HTML:

JavaScript

JavaScript

get_students_list.php:

JavaScript

I’ve tried the above id allocation and I also tried creating a checkbox with javascript with the following code (which didn’t work either, because for one i can’t acces the vue elements from there):

JavaScript

Additional tries:

JavaScript

and

JavaScript

Advertisement

Answer

Note: This refers to the last snippet shown in the question, as the OP changed the question after this answer.

Assuming the server side code & fetching the data works, you don’t need to create the input element by another script, you can simple create it like you do with the <td> elements in the v-for loop:

JavaScript

Note the : (or v-bind: as the verbose option) before the id attribute, this is used to bind data to attributes. See https://v2.vuejs.org/v2/guide/syntax.html#Attributes

Edit: Added working example: https://codesandbox.io/s/stack-overflow-q-59488184-x8m0w

Edit: You also need to bind the result to the vue instance. this in .then does not point to your component. Use a closure for that:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement