how to make radio button checked by default in vuejs?

Viewed 36962

I am using VueJs in project, when page load radio buttton status should be checked status need , after that on change radio button, bellow div should be hide and show. i writen bellow code but it is not working:

html
----
<div id="demo">
  <input type="radio" value="male" v-model="male" v-bind:checked="checked" />
   <input type="radio" value="male" v-model="male" v-bind:checked="unchecked" />
</div>

javascript
---------
new Vue({
    el: '#demo',
  data: {
    checked: true
  },
methods:{
  onChange:function(){
   checked=false;
}
}
})
3 Answers

Now we have to choose between 2 conditions. So we should use input radio group.

<b-form-radio-group v-model="gender">
    <input type="radio" value="female"/>
    <input type="radio" value="male"/>
</b-form-radio-group>

And you can set "female" or "male" as variable "gender" initial value.

data() {
    return {
        ...
        gender: 'female',
        ...
    }
}

If you use radio button as individual element, not as group element. Its v-model variable has to be unique, also we can set as default checked option like this.

<input type="radio" value="female" v-model="gender"/>
<input type="radio" value="1" v-model="isOnline"/>

data() {
    return {
        ...
        gender: 'female',
        isOnline: 0,
        ...
    }
}

In the context of what you provided in the html input value as male appearing twice makes no sense because vue.js model entirely depends on the input value to determine the v-model value in the data method under the script section, it's rather you can add female in one of the input fields if your intention is to switch between male and female, you also don't need v-bind:checked="checked" as vue.js determines the default selected radio item from the v-model(gender) you will specify in data function that will be returned, the below is the change you can make in the input radio fields,

<div id="demo">
  <input type="radio" value="male" v-model="gender"/>
   <input type="radio" value="female" v-model="gender"  />
</div>

Lastly, you can add the below in the data function in the script section,

new Vue({
    el: '#demo',
    data: function(){
    return {
        gender: "female"
    }
}
})

and above functional data option is the best practice other than

new Vue({
    el: '#demo',`enter code here`
    data: {
        gender: "female"
    }
}) 

, for component re usability reason

Related