Get the value of a radio button using jquery [duplicate] - javascript

This question already has answers here:
How to check a radio button with jQuery?
(33 answers)
Closed 6 years ago.
I have this portion of code:
var checkout_options = $("#checkout").find("input[type='radio']");
$('#button-account').on('click', function () {
alert(checkout_options.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<div id="checkout">
<p>Checkout Options:</p>
<label for="register">
<input type="radio" name="account" value="register" id="register" checked>
<b>Register Account</b></label>
<br>
<label for="guest">
<input type="radio" name="account" value="guest" id="guest">
<b>Guest Checkout</b>
</label>
<input type="button" value="Continue" id="button-account">
</div>
What I want it is to get the value of the selected radio button but with my code I only get the first radio button value, the second radio does not work.
Kindly help me fix the error.

You need to use this to refer the element inside the callback. So get value by using this.value or $(this).val() method. Although avoid :checked pseudo-class selector otherwise it only selects the first element.
var selected = $("#checkout").find("input[type='radio']");
selected.change(function(){
alert(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<div id="checkout">
<p>Checkout Options:</p>
<label for="register">
<input type="radio" name="account" value="register" id="register" checked>
<b>Register Account</b></label>
<br>
<label for="guest">
<input type="radio" name="account" value="guest" id="guest">
<b>Guest Checkout</b>
</label>
</div>
You can make it simpler using :radio pseudo-class selector
$("#checkout :radio").change(function() {
alert(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<div id="checkout">
<p>Checkout Options:</p>
<label for="register">
<input type="radio" name="account" value="register" id="register" checked>
<b>Register Account</b>
</label>
<br>
<label for="guest">
<input type="radio" name="account" value="guest" id="guest">
<b>Guest Checkout</b>
</label>
</div>

Your handler is only being attached to the radio button that is checked, so no handler exists for the second radio button. Attach a handler to both radio buttons:
var $radioBtn = $( "#checkout" ).find( "input[type='radio']" );
$radioBtn.on( 'change', function() {
if ( this.checked ) {
alert( this.value );
}
});

It didn't work, because you register the event handler for the initially checked value only. This is how to make it dynamically reflect the value change:
var selected = $("#checkout").find("input[name='account']");
selected.change(function(){
alert($(this).val());
});
This also makes sure that only the current radio button group is included, so you can have additional ones.
Jsfiddle:
https://jsfiddle.net/sjmhdasw/

Just use
$("input[type='radio']").on("change", function() {
console.log(this.id + " checked !");
});
It binds an event listener on all the inputs of type radio !
No need to store the selectors inside a variable (unless you're doing something with it, somewhere else in your code)

Related

JQuery check a checkbox then un-check/disable others with the same name attribute

I have the three input checkboxes all of them have the same name attribute I want one of them is checked then others uncheck and disabled. I want to the jquery code within the function call on function and on change event like this code below or any another way work correctly.
<div class="topmenuitems">
<input type="checkbox" name="menu-item-topitemtypes" value="itemwithouticon" />
<input type="checkbox" name="menu-item-topitemtypes" value="itemwithicon" />
<input type="checkbox" name="menu-item-topitemtypes" value="itemicon" />
</div>
var itemWithIconCheckbox = $('.topmenitems input');
var topItemTypesFunc = function() {
//Jquery code here
};
topItemTypesFunc();
topItemTypeCheckboxes.on( 'change', topItemTypesFunc);
You can do the function you want via radio buttons. Here, I have implemented a simple logic here. When a checkbox is changed ten uncheck checkbox other then the clicked one. Here is an working example.
$('input[name="menu-item-topitemtypes"]').on( 'change', function(){
if($(this).prop('checked')){
$('input[name="menu-item-topitemtypes"]').not($(this)).prop('checked', false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="topmenuitems">
<input type="checkbox" name="menu-item-topitemtypes" value="itemwithouticon" />
<input type="checkbox" name="menu-item-topitemtypes" value="itemwithicon" />
<input type="checkbox" name="menu-item-topitemtypes" value="itemicon" />
</div>
This may help full to you
$('input[type="checkbox"]').on('change', function(){
if($(this).is(':checked')){
$(this).siblings().attr('disabled', 'true');
}else{
$(this).siblings().removeAttr('disabled', 'false');
}
})

how to hide and show named divs according to radio value?

This one is quite similar to my other question on:
how to hide and show named divs according to enum value?
Idea here is slightly different, though. The toggle() jQuery function is related to a radio button which is coded below:
<div id="recurrent">
<label for="recurrent">Recurrent? </label>
<input type="radio" id="idtrue" name="recurrent" value="true">Yes
<input type="radio" id="idfalse" name="recurrent" value="false" checked>No
</div>
The div to toggle is:
<div id="ifRecurrentTrue">
/// something
</div>
And the adapted jQuery from the other question is:
$('#recurrent select').on('change', function () {
var value = this.value;
$('#ifRecurrentTrue').toggle(value == true);
}).change();
I bet it's just a matter of different functions, right?
Again, thanks in advance!
You need to find the input elemetns by its name, so use the attribute equals selector instead of the element selector select
$('#recurrent input[name="recurrent"]').on('change', function() {
$('#ifRecurrentTrue').toggle(this.checked && this.id == 'idtrue');
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="recurrent">
<label for="recurrent">Recurrent?</label>
<input type="radio" id="idtrue" name="recurrent" value="true">Yes
<input type="radio" id="idfalse" name="recurrent" value="false" checked>No
</div>
<div id="ifRecurrentTrue">
/// something
</div>
Did't see the element with select tag on provided code, could be input. Replace select with input like following:
$('#recurrent input').on('change', function () {
var value = this.value;
$('#ifRecurrentTrue').toggle(value == true);
}).change();
$(document).ready(function() {
$('input:radio[name=recurrent]').on('change', function () {
var values = this.value;
$('#ifRecurrentTrue').toggle(values =='true');
}).change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div id="recurrent">
<label for="recurrent">Recurrent? </label>
<input type="radio" id="idtrue" name="recurrent" value="true">Yes
<input type="radio" id="idfalse" name="recurrent" value="false" checked>No
</div>
<div id="ifRecurrentTrue">
/// something
</div>

Event Listener for Multiple Radio Button Groups

How would you have a dynamic Javascript/JQuery event listener to know which radio button group is clicked and retrieve the value of the checked element. For example if I have two radio button groups how would I know which one is clicked? How would I do it for a dynamic number of button groups?
Example of two radio button groups:
<div class="btn-group btn-group-vertical" data-toggle="buttons">
<input type="radio" name="input1" value="option1"/>
<input type="radio" name="input1" value="option2"/>
</div>
<div class="btn-group btn-group-vertical" data-toggle="buttons">
<input type="radio" name="input2" value="option1"/>
<input type="radio" name="input2" value="option2"/>
</div>
Edit: For anyone else wondering which of the following question below so far is "more" right, both are correct as .change(function(e) { is a shortcut for .on('click', function(e) {
Edit 2:Removed ID's
This jquery will execute a callback that print in the console the name and the value of the 'clicked' (not changed) radio button.
$('input:radio').on('click', function(e) {
console.log(e.currentTarget.name); //e.currenTarget.name points to the property name of the 'clicked' target.
console.log(e.currentTarget.value); //e.currenTarget.value points to the property value of the 'clicked' target.
});
try it:
Fiddle
To provide a pure JavaScript solution: create a collection for all your radio type inputs and then loop through them all adding an event listener to each. Using this, you can then access any attributes or properties you wish and, if necessary, the parent element as well.
var inputs=document.querySelectorAll("input[type=radio]"),
x=inputs.length;
while(x--)
inputs[x].addEventListener("change",function(){
console.log("Checked: "+this.checked);
console.log("Name: "+this.name);
console.log("Value: "+this.value);
console.log("Parent: "+this.parent);
},0);
Alternatively, as you mention that the number of groups is dynamic, you might need a live node list, which requires a little extra code to check the input type:
var inputs=document.getElementsByTagName("input"),
x=inputs.length;
while(x--)
if(inputs[x].type==="radio")
inputs[x].addEventListener("change",function(){
console.log("Checked: "+this.checked);
console.log("Name: "+this.name);
console.log("Value: "+this.value);
console.log("Parent: "+this.parent);
},0);
Find the name of the input on the change event.
$('input:radio').on('change', function(e){
var name = e.currentTarget.name,
value = e.currentTarget.value;
$('.name').text(name);
$('.value').text(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="btn-group btn-group-vertical" data-toggle="buttons">
<input type="radio" name="input1" id="input1" value="option1"/>
<input type="radio" name="input1" id="input1" value="option2"/>
</div>
<div class="btn-group btn-group-vertical" data-toggle="buttons">
<input type="radio" name="input2" id="input2" value="option1"/>
<input type="radio" name="input2" id="input2" value="option2"/>
</div>
<p>Name: <b class="name"></b></p>
<p>Value: <b class="value"></b></p>
Edit: For anyone else wondering which of the following question below so far is "more" right, both are correct as .change(function(e) { is a shortcut for .on('click', function(e) {
Yes, .change(function(e) { is a shortcut for .on('click', function(e) {, but when you are working with partial views for example in MVC, with .change(function(e) { the link or buttons in the page lose the hiperlink or don't work correctly, so you have to work with .on('click', function(e) { where the hiperlink work fine.

jquery in yii: Detecting radiobutton losing check mark (checked state)

Given the following code (yes, i know it is perhaps irrelevant in yii, but I added the tag so I update the question with the actual generated html):
<script>
$(function(){
$('#widgetId-form input[name="valueType"]').change(function(){
if ($(this).is(":checked"))
{
console.log("habilitando "+$(this).data("class"));
$("."+$(this).data("class")).prop("disabled", false);
}
else
{
console.log("deshabilitando "+$(this).data("class"));
$("."+$(this).data("class")).prop("disabled", true);
}
}).change();
});
</script>
<div id="widgetId-dialog">
<form id="widgetId-form" action="/support/test" method="post">
<div>
<input id="valueType-single" value="single" data-class="singleValueField" checked="checked" type="radio" name="valueType" />
<label for="single">Valor simple</label>
<input size="6" class="singleValueField" type="text" value="" name="singleValue" id="singleValue" />
</div>
<div>
<input id="valueType-range" value="range" data-class="rangeValueField" type="radio" name="valueType" />
<label for="range">Rango (inicio:fin:intervalo)</label>
<input size="6" class="rangeValueField" type="text" value="" name="rangeValue_start" id="rangeValue_start" />:<input size="6" class="rangeValueField" type="text" value="" name="rangeValue_end" id="rangeValue_end" />:<input size="6" class="rangeValueField" type="text" value="" name="rangeValue_interval" id="rangeValue_interval" />
</div>
</form>
</div>
It doesn't trigger change() when a radio becomes unchecked. This implies: controls are disabled only on initialization (.ready()). change() is not triggered individually by controls losing the checkmark.
Question: how can I detect when a radio button loses the checkmark?
This is a conceptional problem. The radio buttons are seen somehow like one element. For closer information look at Why does jQuery .change() not fire on radio buttons deselected as a result of a namesake being selected?.
So the change-event will always only fire on the newly selected element and not on the deselected radios. You could fix your code like this:
$(function(){
$('#widgetId-form input[name="valueType"]').change(function(){
//could be also hardcoded :
$('input[name="' + $(this).attr("name") + '"]').each(function(){
if ($(this).is(":checked"))
{
console.log("habilitando "+$(this).data("class"));
$("."+$(this).data("class")).prop("disabled", false);
}
else
{
console.log("deshabilitando "+$(this).data("class"));
$("."+$(this).data("class")).prop("disabled", true);
}
});
});
$('#widgetId-form input[name="valueType"]:first').change();
});
You can check it at http://jsfiddle.net/jg6CC/. Greets another Luis M. ;)

How to manually check a YUI radio "button"

<script type="text/javascript">
(function () {
var ButtonGroup = YAHOO.widget.ButtonGroup;
var onCheckedButtonChange = function (p_oEvent) {
};
YAHOO.util.Event.onContentReady("mediaFilterButtonsFieldset", function () {
var oButtonGroup = new ButtonGroup("mediaFilterButtons");
oButtonGroup.on("checkedButtonChange", onCheckedButtonChange);
});
}());
</script>
<div id="resultInfo">
<form id="button-example-form" name="button-example-form" method="post">
<fieldset id="mediaFilterButtonsFieldset">
<div id="mediaFilterButtons" class="yui-buttongroup ie7filter" style="z-index:11;">
<div id="mediaFilterLabel">Go to</div>
<input id="radio1" class="filter_but" type="radio" name="0" value="First" checked rel="0" >
<input id="radio2" class="filter_but" type="radio" name="2" value="Second" rel="2">
<input id="radio3" class="filter_but" type="radio" name="1" value="Third" rel="1">
</div>
</fieldset>
</form>
</div>
These are my YUI buttons. They're just 3 radio buttons turned into "buttons"--literally. My question is this:
After people click the third button, I cannot manually check the first button anymore. How can I manually check "radio1"?
Edit:
According to the official YUI website, there is a method called "set". But I don't know how to use that in this buttonGroup.
The radio buttons must all have the same name attribute in order for them to be grouped together.
Answering your question with the set method. Perhaps this does the trick:
YAHOO.one("#radio1").set("checked",true);
To manually check the radio buttons, it's necessary to have the same name of radio button. Put the same name of radio button and get your result.

Categories

Resources