[Vuejs]-Why is my boolean always true when passing it as value to a radio component?

3πŸ‘

βœ…

The problem is that the value of selected is a string, whereas you expect it to be a boolean.

The following watcher:

watch: {
    selected(newValue) {
        console.log("selected changed to", newValue, "which is a", typeof newValue);
    }
}

Will tell you this:

selected changed to true which is a string 
selected changed to false which is a string

The reason is that you give the fields value a string instead of a boolean. To fix this, instead of writing value="true", write :value="true".

You can play with a live example here.

πŸ‘€papillon

0πŸ‘

There are two problems as far as I can see here:

In a component, the data key must be a function and the value for the selected key in the object returned by the data function must be an actual boolean value true or false (which will be initial value)

export default {
  name: 'CreateTournamentForm',
  data: function(e) {
      return {
        selected: true,
    }
  },
} 

By default, v-model values are treated as strings so your true and false values are actually the strings "true" and "false" which are both truthy. Changing your template code to the below (or alternatively using a number or string value instead) should fix it

<div v-show="selected === 'true'" id="ta-multDays">
    <textarea  rows="10" cols="80" name="multDays" type="text" />
</div> 

0πŸ‘

I solved it by changing it from a β€˜v-show’ to β€˜v-if’

<div>
    <p>One day?</p>
    <input 
        v-model="selected" 
        type="radio" 
        name="oneDay" 
        id="oneDay" 
        class="r-button" 
        value="onlyOneDay" /> 
</div>
<div id="multipleDays">
    <p>Multiple days?</p> 
    <input 
        v-model="selected" 
        type="radio" 
        name="multDays" 
        id="multDays" 
        class="r-button" 
        value="multipleDays" />
</div>

then the div to be shown as follows:

<div v-if="selected === 'multipleDays'" id="ta-multDays">
    <textarea  rows="10" cols="80" name="" type="text" />
</div>

<div v-if="selected === 'onlyOneDay'" id="i-oneDay">
    <input type="text" name="">
</div>
πŸ‘€Ctfrancia

Leave a comment