Sierra Kilo
Sierra Kilo

Reputation: 275

How do I check which radio button is selected when there are multiple radio buttons with the same name? (using jquery)

<form class="responses">
    <input type="radio" name="choice" value="0">False</input>
    <input type="radio" name="choice" value="1">True</input>
</form>

Have tried:

$('[name="choice"]').is(':checked'))

If either is checked it returns true, if neither is checked returns false, but I need to see which one is checked.

I am creating choices dynamically, and am not giving each an ID.

Upvotes: 1

Views: 1974

Answers (5)

Aiyoub A.
Aiyoub A.

Reputation: 5391

try this:

$('input[name=choice]:checked', '#myForm').val()

Script:

$( "#myForm input" ).on( "change", function() {
  $( "#log" ).html( $( "input[name=choice]:checked" ).val() + " is checked!" );
});

HTML:

<form id="myForm">
    <input type="radio" name="choice" value="0">False</input>
    <input type="radio" name="choice" value="1">True</input>
</form>
<div id="log"></div>

$( "#myForm input" ).on( "change", function() {
  $( "#log" ).html( $( "input[name=choice]:checked" ).val() + " is checked!" );
});
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        
        <form id="myForm">
        <input type="radio" name="choice" value="0">False</input>
        <input type="radio" name="choice" value="1">True</input>
        </form>
        <div id="log"></div>

Upvotes: 0

Vikrant
Vikrant

Reputation: 444

Other answers are the perfect one , this can be an another approach

HTML :

<form class="responses">
 <input type="radio" name="choice" class="my_radio" value="0">False</input>
 <input type="radio" name="choice" class="my_radio" value="1">True</input>
</form>

JQUERY:

 $('.my_radio').click(function(){
  alert($(this).val());
 });

Upvotes: 0

brk
brk

Reputation: 50291

The following code will give the value of the checked radio button. If nothig is checked it will give undefined. Put this snippet inside a function and call the function on checking radio button

$("input[name='choice']:checked").val()

Upvotes: 1

Mahbubul Islam
Mahbubul Islam

Reputation: 1018

If you want to know the selected value use

$("input:radio[name='choice']:checked").val();

If you want to know which radio button is selected use

var radioButton = $("input:radio[name='choice']");
var selectedIndex = radioButton.index(radioButton.filter(':checked'));

Upvotes: 1

Frankusky
Frankusky

Reputation: 1083

With the following code you will get the DOM of the checked radio element

$("[name=choice]:checked")

Upvotes: 1

Related Questions