Vuejs radio button binding input - javascript

I am creating edit form page and i run this before the page loaded
beforeMount(){
if(this.$route.meta.mode === 'edit'){
this.initialize = '/api/artikel/edit/' + this.$route.params.id;
this.store = '/api/artikel/update/' + this.$route.params.id;
this.method = 'put';
}
this.fetchData();
},
and in my fetchData() method i just go to server and retrieve corresponding data to my article id.
fetchData(){
var vm = this
axios.get(this.initialize)
.then(function(response){
Vue.set(vm.$data, 'form', response.data.form);
Vue.set(vm.$data, 'rules', response.data.rules);
Vue.set(vm.$data, 'option', response.data.option);
})
.catch(function(error){
})
},
and then in my form i just bind my form data to my input and it works great in input text but not in other like in this question is input radio button
<div class="form-group">
<h5>Publish:</h5>
<label class="radio-inline">
<input type="radio" name="publish" class="styled" value="1" v-model="form.publish">
Yes
</label>
<label class="radio-inline">
<input type="radio" name="publish" class="styled" value="0" v-model="form.publish">
No
</label>
</div>
it supposed to be auto check into radio button according to the value from database... but in my case none of them checked.. but when i check manualy by clicking it... i see using the form.publish value is changed according to which radio button i check using vuejs inspector in chrome
so where do i get it wrong?

Might be a matter of how the value is coming in. Because you set values to 0/1 the radio button model needs a 0 or 1 value, and not a true/false, can you check that that's the case?
look at snipped below, see what changing to true does
new Vue({
el: '#app',
data: {
form: {}
},
methods: {
update () {
// does not work
//var form = { publish: true }
// works
var form = { publish: 1 } // <---- are you sure it's 1 and not true?
this.$set(this, 'form', form);
}
},
mounted() {
console.log(this.form)
setTimeout(this.update, 1000)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.8/vue.min.js"></script>
<div id="app">
<div class="form-group">
<h5>Publish:</h5>
<label class="radio-inline">
<input type="radio" name="publish" class="styled" value="1" v-model="form.publish">
Yes
</label>
<label class="radio-inline">
<input type="radio" name="publish" class="styled" value="0" v-model="form.publish">
No
</label>
</div>
</div>

okay my bad.... it is not a problem with vue.js but instead because i am using uniform.js for my radio button styling from admin template that i bought in themeforest and they don't provide a clear documentation...
and after searching around i find that the javascript and css that style my radiobutton is by uniform.js and i just add a jquery code to run update the radiobutton

I have wasted few hours, and later got to know, I was missing :checked="item.isActive == true" property while binding. Adding this worked for me.
<input
class="form-check-input"
type="radio"
name="students"
v-model="item.isActive"
:checked="item.isActive== true">

Related

Vue JS Radio button toggle all scenario

So I know how I can toggle all radio buttons in a group but I have a slightly niche case here. I'll try and explain as best I can here with code and comments.
SomeComponent.vue
<template>
<div>
<!-- This checkbox will toggle the selected stated of all radios -->
<input class="toggleAll" type="checkbox" :checked="checked" #change="toggleAll">
<!-- These will either toggle their own checked state or
IF the above checkbox has been checked and all checkbox are selected, it would remove the
checked state from that one
as not all the radios ARE selected anymore -->
<input :checked="checked" class="radio" type="checkbox">
<input :checked="checked" class="radio" type="checkbox">
<input :checked="checked" class="radio" type="checkbox">
<input :checked="checked" class="radio" type="checkbox">
</div>
</template>
<script>
export default {
name: 'SomeComponent',
data() {
return {
checked: false,
}
},
methods: {
toggleAll() {
this.checked = !this.checked;
}
}
}
</script>
So basically, the input with the class of toggleAll will check/uncheck all checkboxes. However, checking any of the others should uncheck the one you clicked plus the toggleAll checkbox, as not all are checked anymore.
I can't seem to get this to work! I basically need to say look for the input with the class of toggleAll and change the data "checked" to false but I don't know how to do it.
TIA
If you don't have any specific preference for the checked states, I would recommend using a list of boolean and toggle their respective states (with Vue.set to overcome the array change detection caveat).
The example below uses a computed setter/getter to reactively tell if all checkboxes are checked, and toggle them at once when the setter gets called.
By the way, I added an extra attribute (indeterminate) that you might find useful.
I'm using the .prop modifier on the "allChecked" checkbox to tell Vue that we want to bind this indeterminate as a DOM property instead of component attribute.
new Vue({
el: '#app',
data() {
return {
checkList: [false, false, false, false]
}
},
computed: {
allChecked: {
get() {
return this.checkList.every(Boolean);
},
set(isChecked) {
for (let index = 0; index < this.checkList.length; index++) {
this.$set(this.checkList, index, isChecked);
}
}
},
indeterminate() {
return !this.allChecked && this.checkList.some(Boolean);
}
}
})
#app > input[type="checkbox"] {
display: block;
}
<script src="https://cdn.jsdelivr.net/npm/vue#2.6.11"></script>
<div id="app">
<label>
<input
v-model="allChecked"
:indeterminate.prop="indeterminate"
class="toggleAll"
type="checkbox" />
Check all
</label>
<input
v-model="checkList[index]"
v-for="(checked, index) of checkList" :key="index"
class="radio"
type="checkbox" />
</div>
It could be that your problem comes from the fact that the #change event only fires when a user interacts with the radio and changes. On the other hand, looking at your code, are you trying to change the main button's status using the checkAll method? In that case, what's the toggleAll referencing in #change="toggleAll"?
In any case, this should do it:
<template>
<div>
<input class="toggleAll" type="checkbox" :checked="checked2" #change="toggleAll">
<input :checked="checked" #change="toggleMain" class="radio" type="checkbox">
<input :checked="checked" #change="toggleMain" class="radio" type="checkbox">
<input :checked="checked" #change="toggleMain" class="radio" type="checkbox">
<input :checked="checked" #change="toggleMain" class="radio" type="checkbox">
</div>
</template>
<script>
export default {
name: 'SomeComponent',
data() {
return {
checked: false,
checked2: false
{
},
methods: {
toggleMain() {
this.checked2 = false;
}
...
}
}
</script>

How to get the boolean value based on radio button selected in html using angular

I have created two radio buttons like Order, and Cart as like below, and I just want to get the TRUE (if the radio button is checked and by default Order button is checked) and FALSE if its not checked in app.component.ts file in angular JS.
app.component.html
<div class="container">
<form>
<label class="radio-inline">
<input type="radio" name="optradio" checked id="place_Oreder">Order
</label>
<label class="radio-inline">
<input type="radio" name="optradio" id="add_cart">Cart
</label>
</form>
</div>
I just written the following code which say if there is onclick on both button the boolean value will change:
isSelectedMSM:boolean=false;
isSelectedLive:boolean=false;
$(document).ready(function(){
$("#place_Oreder").click(function(){
this.isSelectedOrder=true;
});
});
$(document).ready(function(){
$("#add_cart").click(function(){
this.isSelectedcart=true;
});
});
I'm not sure that How can I print TRUE or FALSE in app.components file based on the radio button selected by user based on that I need to put if condition and call an appropriate service to invoke.
Can someone help me to achieve this? I just googled but I didn't find the right resource to implement the same. It would be much helpful if someone share your experience to solve this.
Update:
I'm not sure the above code will work. But can someone lead me that how can I achieve this in better way.
A simple click event will do the trick
<label class="radio-inline">
<input type="radio" name="optradio" checked id="place_Oreder" (click)="onClick('order')">Order
</label>
<label class="radio-inline">
<input type="radio" name="optradio" id="add_cart" (click)="onClick('cart')">Cart
</label>
comp.ts
onClick(item) {
if(item == 'order')
this.isSelectedOrder = true;
else if(item == 'cart')
this.isSelectedCart = true;
}
You can use ngForm for this, pass ref to function and from component, get the values as required.
Demo (Check console.)
HTML
<div class="container">
<form #myForm="ngForm" (submit)="submitForm(myForm)">
<label class="radio-inline">
<input ngModel type="radio" name="optradio" checked value="true" id="place_Oreder">Order
</label>
<label class="radio-inline">
<input ngModel type="radio" name="optradio" value="false">Cart
</label>
<button type="submit">Submit</button>
</form>
</div>
Component
submitForm(form: NgForm) {
console.log(form.value);
}

Preventing all checkboxes from being set to true/false when one is clicked

I'm working in Knockout and I'm trying to get specific information when a specific checkbox is checked. However, what's happening is every checkbox is being selected/deselected when I click on one. My question is, how do I prevent that from happening and make it to where only the check box I select/deselect is checked/unchecked?
JS
I've simplified this to show just the code I'm working with.
export class Model{
isSelected: KnockoutObservable<boolean>;
constructor(){
this.isSelected = ko.observable(false);
}
selectStuff = () => {
return true;
}
}
HTML
<div data-bind="foreach: stuffToLoopThrough">
<input type="checkbox" class="checkbox" name="checkBox" data-bind="checked: $root.isSelected, click: $root.selectStuff" />Send Stuff
<input type="checkbox" class="checkbox" name="checkBox" data-bind="checked: $root.isSelected, click: $root.selectStuff" />Send Stuff
<input type="checkbox" class="checkbox" name="checkBox" data-bind="checked: $root.isSelected, click: $root.selectStuff" />Send Stuff
</div>
So what's happening here is, if I were to click on one of the three check boxes, every checkbox would be selected, I want just the check box I selected to be checked. How do I make that happen? Where am I going wrong here?
Are you wanting multiple values selected or just one? If you just want 1 use a radio not a checkbox.
Either way, check out the checkedValue binding which allows you to store results in a variable:
http://knockoutjs.com/documentation/checked-binding.html
var stuffToLoopThrough = Model[];
var selectedValue = ko.observable();
export class Model{
isSelected: KnockoutObservable<boolean>;
constructor(){
this.uniqueValueOrId= ko.observable();
this.isSelected = ko.observable(false);
}
selectStuff = () => {
return true;
}
}
and then the html
<div data-bind="foreach: stuffToLoopThrough">
<input type="radio"
class="radio"
name="checkBox"
data-bind="checked: isSelected,
checkedValue: $root.uniqueValueOrId,
click: $root.selectStuff"> Send Stuff
</div>
notice I am not using the $root for the checked...

how to use template.find() to get the checkbox checked or not?

I have a template that have a checkbox input:
If I use this html
<label class="checkbox-inline">
<input type="checkbox" name="apPartTime"
checked="{{isWorkChecked 'isPartTime'}}">Part Time
</label>
and
let isPartTime = $('[name=apPartTime]').is(':checked');
I can get true or false back, but if I want to use javascript only, how can I get the boolean value?
If the html like this
<label class="checkbox-inline">
<input type="checkbox" id ="apFullTime"
checked="{{isWorkChecked 'apFullTime'}}">Full Time
</label>
and I want to get this checkbox is checked or not
I tried
let isFullTime = template.find('#apFullTime').value;
let isFullTime = template.find('#apFullTime');
None is worked.
If you wrap your checkbox in a form, you could retrieve the value by accessing event.target.myId.checked.
For example:
<template name="myTemplate">
<form class="my-form">
<label class="checkbox-inline">
<input type="checkbox" id="ap-full-time-form">Full Time
</label>
<button type="submit">Submit</button>
</form>
</template>
Template.myTemplate.events({
'submit .my-form'(event, instance) {
event.preventDefault();
let isChecked = event.target["ap-full-time-form"].checked;
console.log(isChecked);
}
});
If you want to register a separate Meteor event for input types, you could access the value directly by using event.target.checked.
For instance:
<template name="myTemplate">
<label class="checkbox-inline">
<input type="checkbox" id="ap-full-time-form">Full Time
</label>
</template>
Template.myTemplate.events({
'click input'(event, instance) {
let isChecked = event.target.checked;
console.log(isChecked);
}
});
In addition, you could simply use instance.find("#myId").checked:
Template.myTemplate.events({
'submit .my-form'(event, instance) {
event.preventDefault();
let isChecked = instance.find("#ap-full-time-form").checked;
console.log(isChecked);
}
});

Validate "yes/no" radio buttons to specific correct values using jQuery Validator plugin

and trying my best to get my head around the jQuery validator plugin.
I have googled extensively, but could not find anything similar to what i am trying to achieve. Please could someone help.
I am trying to build a questionnaire form using radio buttons, and validate them using the jQuery validator plugin.
How would I go about setting the validation rules specific to certain answers being either yes or no values:
<p>Are you a member of our group? <br />
<input type="radio" name="member" value="Yes" class="required" id="memberYes" />
<label for="memberYes">Yes</label> <<<<----User must be a member and select 'Yes'
<input type="radio" name="member" value="No" id="memberNo" />
<label for="memberdNo">No</label>
</p>
<p>Are you currently under investigation? <br />
<input type="radio" name="investigation" value="Yes" class="required" id="investigationYes" />
<label for="investigationYes">Yes</label>
<input type="radio" name="investigation" value="No" id="investigationNo" />
<label for="investigationNo">No</label> <<<<----User must select 'No' or a message pops up to send them to the correct form
</p>
<p>Has your cat turned green? <br />
<input type="radio" name="greenCat" value="Yes" class="required" id="greenCatYes" /> <label for="greenCatYes">Yes</label> <<<<---- User must select 'Yes' This is only for users who's cat's are green
<input type="radio" name="greenCat" value="No" id="greenCatNo" />
<label for="greenCatNo">No</label>
</p>
<p>Are you currently on the diet? <br />
<input type="radio" name="diet" value="Yes" class="required" id="dietYes" />
<label for="dietYes">Yes</label> <<<<----User must select the 'Yes' option.
<input type="radio" name="diet" value="No" id="dietNo" />
<label for="dietNo">No</label>
</p>
I have tried the following methods but none not seem to work:
$('#Form').validate({
rules: {
member:{required: function() {
$('input[name="member"]:checked').val() === 'Yes';
}
},
investigation:{required: function() {
return $('#investigationNo').is(':checked');
}
},
greenCat:{required:true},
diet:{required:'#dietYes:checked'}
}
Kindest Regards, and Thanks in advance for your assistance
I have tried adding a new method, but somehow it does not seem to work.
jQuery.validator.addMethod('correctAnswerRadio', function(value, element) {
var selectedVal = $('input[name='+element+']:checked').val();
alert(element.name + selectedVal + value);
if(selectedVal === value){ //Correct Value
return true;
}else{
return false;
}
});`
i changed this to:
$('#Form').validate({
rules: {
member:{required:true,correctAnswerRadio:'Yes'},
investigation:{required:true,correctAnswerRadio:'No'},
greenCat:{required:true,correctAnswerRadio:'Yes'},
diet:{required:true,correctAnswerRadio:'Yes'}
}
});
The method only alerts 'value' as "Yes" values when correctAnswerRadio:'No'. What could i be doing wrong?
I know it is an old post but google still brings people here.
I've found a simple way to solve it. It's not at the jquery validator's documentation but solved.
First of all you must select one radio. It could be the "No". The value can be any, but I've worked with "True" or "False"
Secondly do this at javascript (assuming your field name is terms)
$('form').validate({
rules:{
terms: {min:"True"}
},
messages:{
terms: {min:'you must accept terms to move on.'}
}
});
I've made an example at jsfiddle: http://jsfiddle.net/ThcS8/117/
Hey i had the same problem, here is a method i used to make it work:
$.validator.addMethod("hasToBeYes", function(value, element) {
var elem_name = $(element).attr('name');
value = $('input:radio[name="'+elem_name+'"]:checked').val();
return(value == 'yes');
}, 'You have to answer "Yes" to this question');
you can just define a second validation method, correctAnswerRadioNo that would check that the radio group has a selected value of 'No', and use it when the 'required' answer is no.
I have managed to solve this in a messy way by having to create a method for every radio button. If someone has a better more efficient way let me know :)
jQuery.validator.addMethod('member', function(value, element, params) {
return $("input[name='member']:checked").val() == 'Yes';
}, "You need to be a member to continue");
jQuery.validator.addMethod('investigation', function(value, element, params) {
return $("input[name='investigation']:checked").val() == 'Yes';
}, "You should not be under investigation to continue");
jQuery.validator.addMethod('greenCat', function(value, element, params) {
return $("input[name='greenCat']:checked").val() == 'Yes';
}, "Your cat must be green to continue");
jQuery.validator.addMethod('diet', function(value, element, params) {
return $("input[name='diet']:checked").val() == 'Yes';
}, "You must be on a diet to continue");
and
rules: {
member:{required:true,member:true},
investigation:{required:true,investigation:true},
greenCat:{required:true,greenCat:true},
diet:{required:true,diet:true}
}
It seems to work well, but the only problem i have now is that the first radio button on first click does not show an error if the incorrect value is selected. after you toggle the radio button selection a bit the correct error appears. could this be a bug?
I had the same problem and I solved it by adding a class "correct" to the specific radio button I want selected, then add a method that checks whether this is checked, and bind the method to the class.
Like this:
<script>
// add new method:
jQuery.validator.addMethod("correct", function(value,element) {
return $(element).is(':checked') ; }, "You must choose this option.");
// bind new method to class "correct":
jQuery.validator.classRuleSettings.correct = { correct:true };
</script>
<html>
<p>Are you a member of our group? <br />
<input type="radio" name="member" value="Yes" class="correct" id="memberYes" />
<label for="memberYes">Yes</label> <<<<----User must be a member and select 'Yes'
<input type="radio" name="member" value="No" id="memberNo" />
<label for="memberdNo">No</label>
<p>Are you currently under investigation? <br />
<input type="radio" name="investigation" value="Yes" id="investigationYes" />
<label for="investigationYes">Yes</label>
<input type="radio" name="investigation" value="No" class="correct" id="investigationNo" />
<label for="investigationNo">No</label> <<<<----User must select 'No' or a message pops up to send them to the correct form
</p>
</html>

Categories

Resources