I use this code for get the value of radio button in jquery, my problem is when I click the option 1 it works fine but when I click on option 2 it not work. Please help!
<form>
Option 1<input type="radio" name="opt" id="radio" value="Option 1">
Option 2<input type="radio" name="opt" id="radio" value="Option 2">
</form>
$('#radio').change(function(){
var value = $( 'input[name=opt]:checked' ).val();
alert(value);
});
JSFiddle: http://jsfiddle.net/khizar067/h6ye7/
The onchange event occurs when the value of an element has been changed. For radiobuttons and checkboxes, the onchange event occurs when the checked state has been changed.
Return value: It returns a Boolean value which represents that the radio button is checked or not.
Please try with the below Demo.
$('input[name=opt]').change(function(){
var value = $( 'input[name=opt]:checked' ).val();
alert(value);
});
http://jsfiddle.net/h6ye7/2/
ID
of elements must be unique, if there are multiple elements with same id then the id selector will return only the first element. so in your case the change event handler is added to only the first radio element
<form>
Option 1<input type="radio" name="opt" class="radio" value="Option 1">
Option 2<input type="radio" name="opt" class="radio" value="Option 2">
</form>
and
//or $('.radio') as the selector
var $radios = $('input[name=opt]').change(function () {
var value = $radios.filter(':checked').val();
alert(value);
});
Demo: Fiddle
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