How to make a radio button checked by default in Vuejs? - vue.js

When the page loads, the radio buttton status should be checked status need, after that on change radio button, bellow div should be hide and show. I wrote the bellow code but it is not working:
html
----
<div id="demo">
<input type="radio" value="male" v-model="male" v-bind:checked="checked" />
<input type="radio" value="male" v-model="male" v-bind:checked="unchecked" />
</div>
javascript
---------
new Vue({
el: '#demo',
data: {
checked: true
},
methods:{
onChange:function(){
checked=false;
}
}
})

Apparently, Vue will check input if bound value is the same with input value:
Check out this fiddle: https://jsfiddle.net/v7zj4c13/188/
<input type="radio" name="gender" value="female" v-model="gender"/>
<input type="radio" name="gender" value="male" v-model="gender"/>
new Vue({
el: '#demo',
data: {
gender: "female"
}
})
Code above will checked the female input, not the male one

Now we have to choose between 2 conditions. So we should use input radio group.
<b-form-radio-group v-model="gender">
<input type="radio" value="female"/>
<input type="radio" value="male"/>
</b-form-radio-group>
And you can set "female" or "male" as variable "gender" initial value.
data() {
return {
...
gender: 'female',
...
}
}
If you use radio button as individual element, not as group element.
Its v-model variable has to be unique, also we can set as default checked option like this.
<input type="radio" value="female" v-model="gender"/>
<input type="radio" value="1" v-model="isOnline"/>
data() {
return {
...
gender: 'female',
isOnline: 0,
...
}
}

In the context of what you provided in the html input value as male appearing twice makes no sense because vue.js model entirely depends on the input value to determine the v-model value in the data method under the script section, it's rather you can add female in one of the input fields if your intention is to switch between male and female, you also don't need v-bind:checked="checked" as vue.js determines the default selected radio item from the v-model(gender) you will specify in data function that will be returned, the below is the change you can make in the input radio fields,
<div id="demo">
<input type="radio" value="male" v-model="gender"/>
<input type="radio" value="female" v-model="gender" />
</div>
Lastly, you can add the below in the data function in the script section,
new Vue({
el: '#demo',
data: function(){
return {
gender: "female"
}
}
})
and above functional data option is the best practice other than
new Vue({
el: '#demo',`enter code here`
data: {
gender: "female"
}
})
, for component re usability reason

Related

Vue-JS v-show Percitence in radio

v-show appears not be percitent when whit radio (v-model)
Please find example: https://jsfiddle.net/Lngocxrj/1/
<div id="helloWorldApp">
<input type="radio" v-model="visible" value="true" name="optradio">hide
<input type="radio" v-model="visible" value="false" name="optradio">show
<div v-show="visible">
Hello World
</div>
<p>
{{visible}}
</p>
</div>
new Vue({
el: "#helloWorldApp",
data: {
visible: true
},
methods: {
show: function() {
this.visible = !this.visible;
}
}
});
It works, if you use a method to toggle the data.
HTML:
<div id="helloWorldApp">
<label>hide<input type="radio" value="false" #click="inputClick(false)" name="optradio" /></label>
<label>show<input type="radio" value="true" #click="inputClick(true)" name="optradio" /></label>
<div v-show="visible">
Hello World
</div>
<p>
{{visible}}
</p>
</div>
JavaScript:
new Vue({
el: "#helloWorldApp",
data: {
visible: false
},
methods: {
inputClick(val) {
this.visible = val;
}
}
});
Added a new property to differentiate input changes and show/hide div
<div id="helloWorldApp">
<input type="radio" v-model="visible" value="true" name="optradio">hide
<input type="radio" v-model="visible" value="false" name="optradio">show
<div v-if="showDiv">
Hello Worlds
</div>
<p>
{{visible}}
</p>
</div>
new Vue({
el: "#helloWorldApp",
data: {
visible: false,
showDiv: true
},
watch: {
visible(val) {
this.showDiv = val;
}
}
});
As per my comment: the reason why your element is showing regardless of the v-show directive is because the values from the checkboxes are being stored as strings and not booleans. And since "false" is actually truthy because it is a string of non-zero length, your div will always be visible.
Quick solution: Perform string comparison
If you want to keep your code as-is, and understanding that you are looking at string values instead of boolean stored in visible, updating your template to use v-show="visible === 'true'" will work.
Note: I do not encourage this method though, because this is a code smell (see further below for a better solution).
new Vue({
el: "#helloWorldApp",
data: {
visible: 'true'
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="helloWorldApp">
<input type="radio" v-model="visible" value="true" name="optradio">hide
<input type="radio" v-model="visible" value="false" name="optradio">show
<div v-show="visible === 'true'">
Hello World
</div>
<p>
{{visible}}
</p>
</div>
A better solution: use checkbox for binary state toggling
This brings us to another issue: since you are toggling a property, a radio button is not the best UI to do that. A checkbox is more appropriate: in this case, you don't need to do dirty strict comparisons:
new Vue({
el: "#helloWorldApp",
data: {
visible: true
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="helloWorldApp">
<input type="checkbox" v-model="visible" checked>visible
<div v-show="visible">
Hello World
</div>
<p>
{{visible}}
</p>
</div>

In vueJS I want to get actual value of the checkbox but I just get true or undefined

In vueJS I want to get actual value of the checkbox but I just get true or undefined.
Here is source code of checkbox.
<input type="checkbox" :value="assessment" :id="assessment+index" class="md-check" v-model="form.assessments[index]">
You need to add true-value and false-value. See the docs: Checkbox:
<input
type="checkbox"
v-model="toggle"
true-value="yes"
false-value="no"
>
// when checked:
vm.toggle === 'yes'
// when unchecked:
vm.toggle === 'no'
For a single checkbox you can use true-value and false-value attributes; for multiple checkboxes, use an array for the v-model:
var app = new Vue({
el: '#app',
data: {
foo: ["One"]
}
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
<input type="checkbox" name="Foo" v-model="foo" value="One"> One<br>
<input type="checkbox" name="Foo" v-model="foo" value="Two"> Two<br>
v-model value is: {{foo}}
</div>

Vuejs - Proper way to clone an element, and append to DOM

I have a HTML input field to enter some information:
<div id="fruitForm">
<div class="inputArea">
<label for="fruit0">Enter Fruit Name</label>
<input id="fruit0"></input>
</div>
</div>
<button #click="newInputField">Add More Fruit Input Fields</button>
<button #click="submit">Submit Fruit</button>
And then I handle that click event:
export default {
data() {
return {
}
},
methods: {
newInputField() {
//Create another input area for users to input fruits
},
submit() {
//Do something here
}
}
}
When a user selects the Add More Fruit Input Fields button, it should create a new input area so that the HTML looks like this:
<div id="fruitForm">
<div class="inputArea">
<label for="fruit0">Enter Fruit Name</label>
<input id="fruit0"></input>
</div>
<div class="inputArea">
<label for="fruit1">Enter Fruit Name</label>
<input id="fruit1"></input>
</div>
</div>
<button #click="newInputField">Add More Fruit Input Fields</button>
<button #click="submit">Submit Fruit</button>
Now, I've been using traditional DOM manipulation methods via vanilla Javascript to accomplish this... stuff like this:
const inputArea = document.getElementsByClassName('inputArea');
And then I change the id's of the input field, and then I use appendChild to add the new input field to the DOM.
So my question is: how should I be cloning this element with vuejs? I feel I'm not approaching this in the vuejs way. Should I be approaching this like a list and using v-for? Or something else?
Avoid direct DOM manipulations with Vue. You can use data property as a model for your template. The answer would be yes, you can and probably should use v-for for what you call cloning:
var demo = new Vue({
el: '#demo',
data: {
counter: 0,
inputs: [{
id: 'fruit0',
label: 'Enter Fruit Name',
value: '',
}],
},
methods: {
addInput() {
this.inputs.push({
id: `fruit${++this.counter}`,
label: 'Enter Fruit Name',
value: '',
});
}
}
});
<script src="https://unpkg.com/vue#2.5.16/dist/vue.js"></script>
<div id="demo">
<div class="inputArea" v-for="input in inputs" :key="input.id">
<label :for="input.id">{{input.label}}</label>
<input :id="input.id" v-model="input.value"></input>
</div>
<button #click="addInput">Add input</button>
</div>

Vue: Binding radio to boolean

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.
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.
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>
I ran into this myself too, the thing to remember is that the value attribute actually shouldn't change for the radio button, what changes (and what you need to bind to) is the checked attribute.
And then you need to handle the change event to set the correct item's value in your data.
Based on your jsFiddle, I think this is what you're looking for:
<div id="l-main">
<div v-for="(variation, key) in variations">
<label>
{{ variation.name }}
<input
type="radio"
name="Test"
:value="key"
:checked="variation.primary"
#change="onChange"
/>
</label>
</div>
<br>Output:<br>
<div v-for="(variation, key) in variations">
{{ variation.name }} {{ variation.primary }}
</div>
</div>
var vm = new Vue({
el: '#l-main',
data: {
variations: {
'41783' : {
'name': 'test1',
'primary': false
},
'41785' : {
'name': 'test2',
'primary': true
}
}
},
methods: {
onChange($event) {
// the primary variation is the one whose key
// matches the value of the radio button that got checked
for (const key in this.variations) {
this.variations[key].primary = key === $event.target.value;
}
}
}
});

vuejs set a radio button checked if statement is true

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.
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.
You can follow below option if you can adjust with your logic:
<div class="combination-quantity">
<input type="radio" value="Lost"
v-model="missing_status">
<label for="lost">Lost</label>
<br>
<input type="radio" value="Return Supplier" v-model="missing_status">
<label for="return_supplier">Return Supplier</label>
</div>
Value for missing_status could be "Lost" or "Return Supplier" and based on the value radio option will be get selected automatically.
Below is an example of keeping track of the selected radiobutton, by
applying a value binding to the object (:value="portal") and
applying a v-model binding to the currently selected object (v-model="currentPortal").
The radiobutton will be checked automatically by Vue, when the two match (no :checked binding necessary!).
Vue 3 with composition API
Vue.createApp({
setup() {
const portals = [{
id: 1,
name: "Portal 1"
}, {
id: 2,
name: "Portal 2"
}];
const currentPortal = portals[1];
return {
portals,
currentPortal
}
}
}).mount("#app");
<script src="https://unpkg.com/vue#next"></script>
<div id="app">
<template v-for="portal in portals">
<input
type="radio"
:id="portal.id"
name="portalSelect"
:value="portal"
v-model="currentPortal">
<label :for="portal.id">{{portal.name}}</label>
</template>
</div>
I would like to point out a few options when dealing with radios and vue.js. In general if you need to dynamically bind an attribute value you can use the shorthand binding syntax to bind to and calculate that value. You can bind to data, a computed value or a method and a combination of all three.
new Vue({
el: '#demo',
data() {
return {
checkedData: false,
checkedGroupVModel: "radioVModel3", //some defaul
toggleChecked: false,
recalculateComputed: null
};
},
computed: {
amIChecked() {
let isEven = false;
if (this.recalculateComputed) {
let timeMills = new Date().getMilliseconds();
isEven = timeMills % 2 === 0;
}
return isEven;
}
},
methods: {
onToggle() {
this.toggleChecked = !this.toggleChecked;
return this.toggleChecked;
},
mutateComputedDependentData() {
this.recalculateComputed = {};
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<div id="demo">
<div>
<div>
<span>Simple Radio Group - Only one checked at a time. Bound to data.checkedData</span><br>
<label>Radio 1 - inverse of checkedData = {{!checkedData}}
<input type="radio" name="group1" value="radio1" :checked="!checkedData">
</label><br>
<label>Radio 2 - checkedData = {{checkedData}}
<input type="radio" name="group1" value="radio2" :checked="checkedData">
</label><br>
<span>Understanding checked attribute: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-checked</span>
</div>
<br>
<div>
<span>Simple Radio - Checked bouned to semi-random computed object</span><br>
<label>Radio 1: {{amIChecked}}
<input type="radio" :checked="amIChecked">
</label>
<label>Recalculate Computed Value
<button type="button" #click="mutateComputedDependentData">Click Me Several Times</button>
</label>
</div>
<br>
<div>
<span>Simple Radio Group - v-model bound value = {{checkedGroupVModel}}</span><br>
<label>Simple Radio 1:
<input type="radio" name="vModelGroup" value="radioVModel1" v-model="checkedGroupVModel">
</label><br>
<label>Simple Radio 2:
<input type="radio" name="vModelGroup" value="radioVModel2" v-model="checkedGroupVModel">
</label><br>
<label>Simple Radio 3:
<input type="radio" name="vModelGroup" value="radioVModel3" v-model="checkedGroupVModel">
</label>
</div>
<br>
<div>
<span>Simpe Radio - click handler to toggle data bound to :checked to toggle selection</span><br>
<label>Toggle Radio = {{toggleChecked}}
<input type="radio" :checked="toggleChecked" #click='onToggle()'>
</label>
</div>
</div>
</div>