I'm new in Vue, and I'm really in doubt about something. Well, I'm in doubt about the way we handle click event in Vue and jQuery. For me, at this moment, jQuery seems to be more simple to achieve.
in jQuery we just do that:
HTML:
<div class="jquery-radio">
Radio 1 <input type="radio" name="radio" class="choose-radio" value="Radio1" checked>
<br>
Radio 2 <input type="radio" name="radio" class="choose-radio" value="Radio2">
jQuery
$('.choose-radio').click(function() {
$('.choose-radio:checked').val() == 'Radio1' ? alert('Radio 1') :
$('.choose-radio:checked').val() == 'Radio2' && alert('Radio 2 ');
});
So, my doubt is. How to achieve this, using Vue? I tried to do this, but as I said, jQuery seems to be more simple, because instead of add #click="myMethod()" i just do what I want, selecting the element (class) $('.choose-radio);
HTML:
<div class="jquery-radio">
Radio 1 <input type="radio" name="choose-radio-vue" class="choose-radio-vue" value="Radio1" checked #click="showRadio1()">
<br>
Radio 2 <input type="radio" name="choose-radio-vue" class="choose-radio-vue" value="Radio2" #click="showRadio2()">
Vue
var app = new Vue ({
el: ".jquery-radio",
methods: {
showRadio1: function() {
alert("Show 1");
},
showRadio2: function() {
alert("Show 2");
}
}
});
Check Fiddle
These examples above, is basic. In my project, I'll show different sections based on the value previously chosen in radio. I'm realy confused in Vue.
Hope you guys can clarify this information for me!
You can add the same handler and pass in the event object, which you can later use to retrieve the current element. Here's an working example:
var app = new Vue ({
el: ".jquery-radio",
methods: {
show: function(event) {
var value = event.target.value
console.log(value)
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.min.js"></script>
<div class="jquery-radio">
Radio 1
<input type="radio" name="choose-radio-vue" class="choose-radio-vue" value="Radio1" checked #click="show($event)">
<br>
Radio 2
<input type="radio" name="choose-radio-vue" class="choose-radio-vue" value="Radio2" #click="show($event)">
</div>
PS: also, your jQuery approach is far from optimal, as it may yield errors if there are more elements that have the .choose-radio class. What you need is something like:
$('.choose-radio').click(function() {
var value = $(this).val() // value of the selected object
});
It's a pretty different way of thinking. With Vue you want to change data and let Vue handle the DOM manipulation for you. I'd use v-model and toggle the visibility of sections based on that.
new Vue({
data: {
section: 'Radio 1'
}
}).$mount('#app')
label {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.js"></script>
<div id="app">
<label><input name="section" type="radio" v-model="section" value="Radio 1"> One</label>
<div v-if="section === 'Radio 1'">
Radio One Is Selected!
</div>
<label><input name="section" type="radio" v-model="section" value="Radio 2"> Two</label>
<div v-if="section === 'Radio 2'">
Radio Two Is Selected!
</div>
<label><input name="section" type="radio" v-model="section" value="Radio 3"> Three</label>
<div v-if="section === 'Radio 3'">
Radio Three Is Selected!
</div>
</div>
Related
Radio buttons, the first one is checked by default:
<div class="shipping">
<div class="title">Select shipping method</div>
<label><input type="radio" name="shipping" value="courier-dpd" checked="checked">Courier DPD</label>
<label><input type="radio" name="shipping" value="personal">Personal pick up</label>
<button>Next</button>
</div>
Js:
$(document).on('click', '.shipping button', function() {
let val = $('.shipping').find('input[name="shipping"]:checked').val()
console.log(val);
}
Even if I manually switch the radio buttons and select the second one, jQuery keeps getting the value of the first radio button, independently on user selection.
Why is that? I can't find solution.
Edit 2: Added JS code from updated question. It seems to work here.
Edit: Added submit button to demonstrate submit action.
Well, are you calling console.log after changing the value? I created a snippet below and it works fine.
$(function() {
let val = $('.shipping').find('input[name="shipping"]:checked').val()
console.log(val);
/*$('#btn').on('click', function() {
let val = $('.shipping').find('input[name="shipping"]:checked').val()
console.log(val);
})*/
$(document).on('click', '.shipping button', function() {
let val = $('.shipping').find('input[name="shipping"]:checked').val()
console.log(val);
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="shipping">
<div class="title">Select shipping method</div>
<label><input type="radio" name="shipping" value="courier-dpd" checked="checked">Courier DPD</label>
<label><input type="radio" name="shipping" value="personal">Personal pick up</label>
<button>Next</button>
</div>
I have a page with radiobuttons and checkboxes; the form has previously been filled out by the user. I need to bring the form back up for them to edit the EXISTING data, which means I have to programmatically check checkboxes and check radio buttons.
If I HAD an event, I could easily change the corresponding control with srcElement, but there is no event in this case. I haven't been able to find a way with document.getElementById('XXX'). ??? to work in any way.
Using Angular 4 if that helps.
Thoughts?
Thanks in advance, :-)
Use data binding. Then you can set the changed value and the checkbox and radio buttons will check/select automatically.
Here is an example:
<label>
<input id="sendCatalogId"
type="checkbox"
[(ngModel)]="sendCatalog"
name="sendCatalog" >
Send me your catalog
</label>
And a radio button:
<label class="radio-inline">
<input type="radio" id="addressType1Id" value="home"
[(ngModel)]="addressType"
name="addressType">Home
</label>
<label class="radio-inline">
<input type="radio" id="addressType1Id" value="work"
[(ngModel)]="addressType"
name="addressType">Work
</label>
<label class="radio-inline">
<input type="radio" id="addressType1Id" value="other"
[(ngModel)]="addressType"
name="addressType">Other
</label>
This in the component class:
...
export class CustomerComponent {
sendCatalog = false;
addressType = "home";
constructor() {
sendCatalog = true;
addressType = "work";
}
}
I'm not sure if I'm just stuck in a jQuery mindset but is there a way to update 2 model attributes with one radio button? Currently I have 2 radio buttons with one hidden. The visible one checks the second with an #click event that gets the next input and sets it to true.
var app = new Vue({
data: {
order: {
amount:
type:
}
},
methods: {
selectType: function(e) {
e.currentTarget.getElementSibling.checked = true;
}
}
});
<form>
<input type="radio" v-model="order.amount" value=15 #click="selectType">$15</input><br>
<input type="radio" v-model="order.type" value="small" style="display:none">
<input type="radio" v-model="order.amount" value=15 #click="selectType">$15</input><br>
<input type="radio" v-model="order.type" value="med" style="display:none" #click="selectType">
<input type="radio" v-model="order.amount" value=20 >$20</input><br>
<input type="radio" v-model="order.type" value="large" style="display:none">
</form>
The way I understand it, the v-model syntax is best for binding a single value. You could try to somehow make the value a JSON string and then decode it... but that sounds like a bad idea. Here are three ideas:
Using JQuery and Vue
Instead, you could give the radio buttons attributes for each value you want, and then parse out those attributes on the click callback. For example:
<input type="radio" name="rad" btn-amount="10" btn-type="small" #click="selectType($event)">$15 <br>
<input type="radio" name="rad" btn-amount="15" btn-type="med" #click="selectType">$15<br>
<input type="radio" name="rad" btn-amount="20" btn-type="large" #click="selectType">$20<br>
and then a method:
selectType: function(e) {
this.order.amount = $(e.currentTarget).attr('btn-amount');
this.order.type = $(e.currentTarget).attr('btn-type');
}
Here's a JSFiddle showing it in action.
Using Vue only
Alternatively, you could move the data for the options into the vue instance, rather than placing them on on the radio buttons. For example, add an options array to the data, and iterate over it in the HTML to create the buttons
<div v-for="option in options">
<input type="radio" name="rad" #click="selectType(option)">${{ option.amount }}
</div>
Notice that you can pass the current option in the for loop to the click handler! That means you can write selectType as:
selectType: function(option) {
this.order = option;
}
This is very clean, and what I recommend if you plan on keeping the radio-button functionality simple.
Here is a JSFiddle showing it in action.
Using Vue Components
But, if you plan on making things more complex you may want to encapsulate the radio button functionality into a component.
Consider the template:
<template id="radio-order">
<div>
<input type="radio" :name="group" #click="setOrder">${{ amount }}
</div>
</template>
and its associated component:
Vue.component('radio-order', {
template: '#radio-order',
props: ['group', 'amount', 'type'],
methods: {
'setOrder': function() {
this.$dispatch('set-order', {
amount: this.amount,
type: this.type
})
}
}
});
Now you can make <radio-order> components that dispatch a set-order event when clicked. The parent instance can listen for these events and act appropriately.
Admittedly, this method is more verbose. But, if you're thinking of implementing more complex functionality, it's probably the way to go.
Here's a JSFiddle of it in action.
Of course, there are many more ways to solve the problem, but I hope these ideas help!
I have a radio button like this on page
<div id="someId">
<label class="radio-inline">
<input name="x" type="radio" onchange="GetSelectedVal();">Yes</label>
<label class="radio-inline">
<input name="x" type="radio" onchange="GetSelectedVal();">No</label>
</div>
On page load I don't want to set any selection so not using checked property. In my JavaScript function, how can I get the value Yes or No based on the user selection at runtime?
function GetSelectedVal() {
console.log($('#someId input:radio.........);
}
I have seen similar questions but unable to find solution of this issue.
Remove onchange inline handler from HTML. Use on to bind events.
:checked will select the checked radio button. closest will select the parent label and text() will get the label associated with the radio button. e.g. Yes
$('[name="x"]').on('change', function () {
alert($('[name="x"]:checked').closest('label').text());
});
DEMO
You can simple pass this in onchange="GetSelectedVal(); like onchange="GetSelectedVal(this);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="someId">
<label class="radio-inline"><input name="x" type="radio" onchange="GetSelectedVal(this);">Yes</label>
<label class="radio-inline"><input name="x" type="radio" onchange="GetSelectedVal(this);">No</label>
</div>
<script>
function GetSelectedVal(ele) {
alert($(ele).closest('label').text());
}
</script>
I would do it a bit different than the accepted answer.
Instead of having events on multiple radio buttons, you can have one on the containing div. Also let just the checked radio trigger the change:
$('#someId').on('change', 'input[name="x"]:checked', function () {
var label = $(this).siblings('span').text();
console.log(label);
});
When I have text next to other elements I prefer wrapping the text in span's:
<div id="someId">
<label class="radio-inline"><input name="x" type="radio"><span>Yes</span></label>
<label class="radio-inline"><input name="x" type="radio"><span>No</span></label>
</div>
A demo: jsfiddle.net/qcxgwe66/
Am relatively new to what I am doing here. I am just putting together stuff with what I find here and other open resources.
The problem I am having is - With the current setup a person can choose a radio button and check a couple boxes and goto the other radio button option and choose boxes under that. I am trying to get the Checkboxes to be All Checked when someone selects the radion option and UncheckALL when the person chooses another option on the radio button group.
So if I select option 'a' under 'GENERAL' and then goto 'DETAILED' - 'a' should be unchecked.
Heres the code I am using in JFiddle
HTML:
<div id="RadioWidget">
<label><input type="radio" name="chkboxs" value="General" />General Clean</label>
<label><input type="radio" name="chkboxs" value="Detailed" />Detailed Clean</label>
<label><input type="radio" name="chkboxs" value="Commercial" />Commercial Clean</label>
</div>
<div id="General" class="desc">
<p class="maintextBlue">General
<label><input type="checkbox" name="GeneralOptn[]" value="a" />a</label>
<label><input type="checkbox" name="GeneralOptn[]" value="b" />b</label>
</p>
</div>
<div id="Detailed" class="desc">
<p class="maintextBlue">Detailed
<label><input type="checkbox" name="DetailedOptn[]" value="a" />a</label>
<label><input type="checkbox" name="DetailedOptn[]" value="b" />b</label>
</p>
</div>
<div id="Commercial" class="desc">
<p class="maintextBlue">Commercial
<label><input type="checkbox" name="CommercialOptn[]" value="a" />a</label>
<label><input type="checkbox" name="CommercialOptn[]" value="b" />b</label>
</p>
</div>
Jscript:
$(document).ready(function() {
$("div.desc").hide();
$("input[name$='chkboxs']").click(function() {
var test = $(this).val();
$("div.desc").hide();
$("#" + test).show();
});
});
This was a piece of script I found that inverts the checkbox state. But not sure how to integrate it to the radio button. this snippet was working off a onClick() fn for a button.
$("A[href='#invert_selection']").click( function() {
$("#" + $(this).attr('rel') + " INPUT[type='checkbox']").each( function() {
$(this).attr('checked', !$(this).attr('checked'));
});
return false;
});
Any help is much appreciated...
this requires you to add IDS to your input fields... but it would work.
If you want to control multiple input fields you can always uses classes to..
jQuery("#generalA").click(function(){
if(jQuery(this).is(':checked')){
// is checked do some stuff if you want
}else{
// is mot checked uncheck the checkbox with an ID of #detailedA
jQuery('#detailedA').prop('checked', false);
}
return false;
});
The above response by AndrewMac helped.
I just had to figure out a way it helped my existing setup.
Below is the small addition I did to get the desired setup - this way it actually disables all the unnecessary inputs thereby eliminated from the final send out of the form.
$(document).ready(function() {
$("div.desc").hide().find('input, textarea').prop('disabled', true);;
$("input[name$='chkboxs']").click(function() {
var test = $(this).val();
$("div.desc").hide().find('input, textarea').prop('disabled', true);;
$("#" + test).show().find('input, textarea').prop('disabled', false);;
});
});
I have also updated the same on my fiddle page. Fiddle
Thanks for the help AndrewMac - Sorry for the long time to post this response/answer.