Vue: Binding radio to boolean

18,272

Solution 1

To bind radio buttons to boolean values instead of string values in Vue, use v-bind on the value attribute:

<input type="radio" v-model="my-model" v-bind:value="true">
<input type="radio" v-model="my-model" v-bind:value="false">

I'll leave it to you to figure out how to match these values with your backend data.

Checkboxes are not so good for this scenario; the user could leave them both blank, and you don't get your answer. If you are asking a yes/no or true/false question where you want only one answer, then you should be using radio buttons instead of checkboxes.

Solution 2

What you are looking for is a checkbox. Here is an updated jsfiddle.

Your use case is not how radio buttons are supposed to work.

Look at this example.

new Vue({
  el: '#app',
  data: {
    picked: 'One',
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.1/vue.js"></script>
<div id="app">
  <input type="radio" id="one" value="One" v-model="picked">
  <label for="one">One</label>
  <br>
  <input type="radio" id="two" value="Two" v-model="picked">
  <label for="two">Two</label>
  <br><br>
  <span>Picked: {{ picked }}</span>
</div>
Share:
18,272

Related videos on Youtube

Krillko
Author by

Krillko

Working in e-commerce.

Updated on September 14, 2022

Comments

  • Krillko
    Krillko over 1 year

    I'm having trouble binding radiobuttons to boolean values in model.

    In this example: https://jsfiddle.net/krillko/npv1snzv/2/

    On load, the radio radio button is not checked, and when I try to change them, the 'primary' value in model is becomes empty.

    I've tried:

    :checked="variation.primary == true"
    

    but with no effect.

  • Krillko
    Krillko almost 7 years
    I've seen the documentation for it, but I'm matching data from backend, and was hoping to do it directly in vue.
  • Ikbel
    Ikbel almost 7 years
    v-model is giving null because your radio button value attribute is null