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.
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.
If a radio button is checked, its checked property is true .
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.
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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With