Vuejs radio buttons checked if v-model is an array

mtleppay picture mtleppay · Aug 4, 2018 · Viewed 7.1k times · Source

How can i have checked radio button in v-for, if i my v-model is an array?

my data:

data() {
     return {
         persons: {
             name: [],
             surname: [],
             sex: [],
         }
     }
 }  

and my radio:

<template v-for(person, person_index) in persons>
<div class="switch-sex">
   <input type="radio" name="sex" :id="'male'+person_index" value="male"
   v-model="persons.sex[person_index]">
   <label :for="'male' + person_index">M</label>
   <input type="radio" name="sex" :id="'female' + person_index" 
    value="female" v-model="persons.sex[person_index]">
   <label :for="'female' + person_index">F</label>
</div>
</template>

I need my first radio ( male) be checked in each person inside v-for

Answer

gil picture gil · Aug 4, 2018

If I don't misunderstood your question and your objective, your doing dynamic forms for multiple persons then try like this

Template

 //n and index used for 0-based looping

 <div v-for="(n, index) in noOfPersons" :key="index">
     Person {{ index + 1 }}
     <div class="switch-sex">
        <input type="radio" :name="'sex'+(index+1)"  value="male" v-model="persons[index].sex">
        <label >Male {{index+1}}</label>
     </div>
     <div>
        <input type="radio" :name="'sex'+(index+1)" value="female" v-model="persons[index].sex">
        <label >Female {{index+1}} </label>
     </div>
 </div>

Script (just an example to show its checked)

 data() {
    return {
        noOfPersons: 2,
        persons: [
            {name: '', surname: '', sex: 'male'},
            {name: '', surname: '', sex: 'female'},
        ]
    }
}

For those using Vuetify.js (it's different approach with v-model on the v-radio-group wrapper)

 <v-radio-group v-model="persons[index].sex" :mandatory="false">
     <v-radio label="Male" :value="1" color="blue"></v-radio>
     <v-radio label="Female" :value="0" color="blue"></v-radio>
 </v-radio-group>

Here's the Code Pen

NOTE. It is recommended to use binary (0/1) data like 0 for male or 1 for female or other numbers like 1/2 Database Storage / ISO 5218 or dummy variables. Here's explanation