Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vuejs set a radio button checked if statement is true

Tags:

vue.js

I am trying to make a radio button checked using vuejs v-for only if my if-statement is true. Is there a way to use vuejs' v-if/v-else for this type of problem?

in php and html I can achieve this by doing the following:

<input type="radio" <? if(portal.id == currentPortalId) ? 'checked="checked"' : ''?>> 

Below is what I have so far using vuejs:

    <div v-for="portal in portals">      <input type="radio" id="{{portal.id}}" name="portalSelect"        v-bind:value="{id: portal.id, name: portal.name}"        v-model="newPortalSelect"        v-on:change="showSellers"        v-if="{{portal.id == currentPortalId}}"        checked="checked">      <label for="{{portal.id}}">{{portal.name}}</label>     </div> 

I know the v-if statement here is for checking whether to show or hide the input.

Any help would be very much appreciated.

like image 595
rniocena Avatar asked Jan 18 '16 22:01

rniocena


People also ask

How do you checked radio button in VUE JS?

If you see in the input checked property, we insert a condition that will compare the model value against the value. If it is matched, it will then return a true value which will set the radio button to be checked.

Does radio button have checked value?

If a radio button is checked, its checked property is true .

How do you check checkbox is checked or not in VUE JS?

To watch for checkbox clicks in Vue. js, we can listen to the change event. to add the @change directive to the checkbox input to listen to the change event. Then we can get the checked value of the checkbox with e.


2 Answers

You could bind the checked attribute like this:

<div v-for="portal in portals">   <input type="radio"          id="{{portal.id}}"          name="portalSelect"          v-bind:value="{id: portal.id, name: portal.name}"          v-model="newPortalSelect"          v-on:change="showSellers"          :checked="portal.id == currentPortalId">    <label for="{{portal.id}}">{{portal.name}}</label> </div> 

Simple example: https://jsfiddle.net/b4k6tpj9/

like image 176
Pantelis Peslis Avatar answered Nov 11 '22 12:11

Pantelis Peslis


Maybe someone finds this approach helpful:

In template I assign each radio button a value:

<input type="radio" value="1" v-model.number="someProperty"> <input type="radio" value="2" v-model.number="someProperty"> 

Then in the component I set the value, i.e:

data: function () {     return {         someProperty: 2     } } 

And in this case vue will select the second radio button.

like image 45
Aleph-null Avatar answered Nov 11 '22 11:11

Aleph-null