Home » vue » Conditional rendering works to make a form item visible, but unable to hide it

Conditional rendering works to make a form item visible, but unable to hide it

Posted by: admin November 26, 2021 Leave a comment

Questions:

I am wanting to have a textarea element either visible or invisible based on the state of the radio buttons ahead of it. If “no” is selected, then the textarea element will be hidden, and if “yes” is selected, the textarea element will be visible.

<fieldset class="input-group form-check form-check-inline">
    <input type="radio" v-model="elementIsVisible" 
           class="form-check-input" name="myFormInput" 
           id="myFormInputNo" value="false" required>
    <label for="myFormInputNo">No</label>

    <input type="radio" v-model="elementIsVisible"
           class="form-check-input" name="myFormInput" 
           id="myFormInputYes" value="true" required>
    <label for="myFormInputYes">Yes</label>
</fieldset>

<textarea v-if="elementIsVisible" class="form-control"></textarea>
<p>Debug: {{ elementIsVisible }}</p>
export default {
    data: function () {
        return {
            elementIsVisible: false
        }
    }
}

The initial behavior of this works as expected, with the element being shown when choosing “yes”, but if you change the radio button back to “no”, then the textarea element maintains its visible state.

The debug element functions as expected, “yes” being displayed when the yes radio button is selected, and “no” when the no radio button is selected.

Answers:

The issue is the value of radio button by default is a string, not a boolean like you are expecting. The string of value 'true' is truthy as is the string of value 'false' which would make v-if always display the textarea. At minimum use :value instead of value to have the value be actually a boolean that can be used with v-if to conditionally display the textarea:

<div>
  <fieldset class="input-group form-check form-check-inline">
    <input type="radio" v-model="elementIsVisible" class="form-check-input" name="myFormInput" id="myFormInputNo" :value="false" required>
    <label for="myFormInputNo">No</label>
    <input type="radio" v-model="elementIsVisible" class="form-check-input" name="myFormInput" id="myFormInputYes" :value="true" required>
    <label for="myFormInputYes">Yes</label>
  </fieldset>
  <textarea v-if="elementIsVisible" class="form-control"></textarea>
  <p>Debug: {{ elementIsVisible }}</p>
</div>

Here is an example in action. It demonstrates the textarea being added/removed from the DOM.

Hopefully that helps!

###

I haven’t used much Vue, but try replacing the v-if with a v-show. It looks like v-show is recommended if the visibility changes often.

https://vuejs.org/v2/guide/conditional.html#v-if-vs-v-show