[Vuejs]-For loop – bind dynamic key to the #id

3πŸ‘

βœ…

It renders with choice-id string because you add plain string as the id value, not a variable value

You can use v-bind directive or the shorthand for v-bind -> :id

<div class="radio" >
  <label v-for="(choice, index) in choices" v-if="choice.question_id == question.id" :key="choice.id">
      <input type="radio" name="optradio" v-bind:id="choice.id"> [[choice.content]]
  </label>
</div>

using shorthand <input type="radio" name="optradio" :id="choice.id">

To answer your questions in the comments.

You can β€˜ separate β€˜the radios by adding them in a β€˜ group β€˜ using the name attribute. Radios with the same name attribute are in one group. Changing their values won’t affect other radios in other groups ( with different name attributes ). See example below.

Or you can use vue v-model to separate and get the selected options.

new Vue({
  el: "#radio-app",
  data: {
    question1: '',
    question2: ''
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://github.com/vuejs/vue-devtools"></script>
Question1:
<input type="radio" name="question1" id="q1choice1" value="choice1"/>
<input type="radio" name="question1" id="q1choice2" value="choice2"/>
Question2:
<input type="radio" name="question2" id="q2choice1" value="choice1"/>
<input type="radio" name="question2" id="q2choice2" value="choice2"/>
<hr />
<h2> Or with VUE v-model </h2>
<div id="radio-app">
Question1:
  <input type="radio" id="q1choice1vue" value="choice1" v-model="question1">
  <input type="radio" id="q1choice2vue" value="choice2" v-model="question1">
Question2:
  <input type="radio" id="q2choice1vue" value="choice1" v-model="question2">
    <input type="radio" id="q2choice2vue" value="choice2" v-model="question2">
  <div>Question 1 selected answer: {{ question1 }}</div>
  <div>Question 2  selected answer: {{ question2 }}</div>
</div>

Check more here

πŸ‘€Mihai T

0πŸ‘

Use: v-bind:id="choice.id" or the short version :id="choice.id"

Leave a comment