Reputation: 423
I am trying to add radio buttons to my code. Everything works fine except one thing. When I am using v-for loop for creating radios, the default radio is not getting checked. It works if, I put it outside the for loop.
I have tried this :-
:checked="index == 1"
and this ( as suggested in some answers ):-
:checked="{ index == 1 }"
But none of them is working for me.
Below is my template snippet:-
<div class="props-data">
<!-- <input type="radio" :checked="currentStep==1"> -->
<span v-for="(shape, index) in availableShapes" v-if="currentStep==1">
<div>
<input type="radio" :id="shape" :value="shape" v-model="selectedShape" :checked="index == 1">
<label :for="shape">{{shape}}</label>
</div>
</span>
</div>
Note:- steps-container is the main parent class where Vue instance is being created.
Below is my js code:-
window.onload = function(){
new Vue({
el: '#steps-container',
data: function() {
return {
currentStep: 1,
availableShapes: ['Rectangle','Circle','Square','Ellipse'],
selectedShape: undefined
};
},
methods: {
cancel: function(){
this.currentStep = 1;
jQuery('#main-action').text('Go to step '+ (this.currentStep+1));
},
nextStep: function(){
if( this.currentStep == 2 ){
jQuery('#main-action').text('Startover');
this.currentStep++;
}
else{
if( this.currentStep == 3 ){
this.currentStep = 1;
}
else{
this.currentStep++;
}
jQuery('#main-action').text('Go to step '+ (this.currentStep+1));
}
}
},
mounted: function(){
},
updated: function(){
}
});
}
Any help would be much appreciated.
Upvotes: 0
Views: 563
Reputation: 20845
You won't need to set the checked
attr yourself. By using v-model="selectedShape"
you have linked all the radio input with selectedShape
.
You can already control the checked attr by controlling the value of selectedShape
.
So set the initial value of selectedShape
to the default value, and it will be checked by default.
<input type="radio" :id="shape" :value="shape" v-model="selectedShape">
(remove :checked="index == 1"
)
data: function() {
return {
//...
selectedShape: "THE DEFAULT VALUE"
};
},
Upvotes: 1