Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get radio button value on change not working

Tags:

jquery

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/

like image 639
khkhizar Avatar asked Sep 28 '13 07:09

khkhizar


People also ask

Does radio button have Onchange?

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.

Do radio buttons return Boolean?

Return value: It returns a Boolean value which represents that the radio button is checked or not.


2 Answers

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/

like image 194
Jayesh Goyani Avatar answered Oct 14 '22 08:10

Jayesh Goyani


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

like image 26
Arun P Johny Avatar answered Oct 14 '22 08:10

Arun P Johny