Reputation: 167
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/
Upvotes: 15
Views: 65416
Reputation: 18803
$('input[name=opt]').on('change',function () {
alert($(this).filter(':checked').val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
First Option<input type="radio" name="opt" class="radio" value="First Option">
Second Option<input type="radio" name="opt" class="radio" value="Second Option">
</form>
Upvotes: 0
Reputation: 593
<form id="abcd">
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>
$('#abcd').on('change','input[name=opt]:checked',function(){
var value = $(this).val();
alert(value);
});
Upvotes: 4
Reputation: 6101
Try this, this is help you, if you use use multiple radio button then you don't need to get id or class of element you simply get element property by there tag name..
There are several example on this
1.By tag name(All radio button can be select)
$('input[type=radio]').change(function(){
var value = $( 'input[name=opt]:checked' ).val();
alert(value);
});
2.By class name(Multiple radio button can be select)
$('.radiobutton').change(function(){
var value = $( 'input[name=opt]:checked' ).val();
alert(value);
});
3.By id (one radio button select only)
$('#radiobutton').change(function(){
var value = $( 'input[name=opt]:checked' ).val();
alert(value);
});
Fiddle Here
Upvotes: 2
Reputation: 11154
Please try with the below Demo.
$('input[name=opt]').change(function(){
var value = $( 'input[name=opt]:checked' ).val();
alert(value);
});
Upvotes: 46
Reputation: 1700
The id
should be unique, try using class instead:
Html:
<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>
Js:
$('.radio').change(function(){
var value = $( this ).val();
alert(value);
});
Demo Fiddle
Upvotes: 6
Reputation: 388316
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
Upvotes: 13