1
<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.

4
  • 2
    $('form.responses')[0].choice.value Commented Aug 21, 2017 at 4:09
  • @JaromandaX thanks, this works, I'm trying to understand it, I can't figure out what the [0] is. I thought it might be the index of something, but doesn't look like it is. Commented Aug 21, 2017 at 4:15
  • 2
    jquery returns an array-like object, so you want to access the first item ... without jquery, you can do document.querySelector('form.responses').choice.value instead Commented Aug 21, 2017 at 4:17
  • if you give the form an id="fred" for example, even easier ... document.forms.fred.choice.value Commented Aug 21, 2017 at 4:18

5 Answers 5

1

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()
0
1

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

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

1

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'));
0
0

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());
 });
0

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>

Not the answer you're looking for? Browse other questions tagged or ask your own question.