javascript – How can I know which radio button is selected via jQuery?

The Question :

2786 people think this question is useful

I have two radio buttons and want to post the value of the selected one. How can I get the value with jQuery?

I can get all of them like this:

$("form :radio")

How do I know which one is selected?

The Question Comments :

The Answer 1

4021 people think this answer is useful

To get the value of the selected radioName item of a form with id myForm:

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

Here’s an example:

$('#myForm input').on('change', function() {
   alert($('input[name=radioName]:checked', '#myForm').val()); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;</script&gt;
<form id="myForm"&gt;
  <input type="radio" name="radioName" value="1" /&gt; 1 <br /&gt;
  <input type="radio" name="radioName" value="2" /&gt; 2 <br /&gt;
  <input type="radio" name="radioName" value="3" /&gt; 3 <br /&gt;
</form&gt;

The Answer 2

421 people think this answer is useful

Use this..

$("#myform input[type='radio']:checked").val();

The Answer 3

314 people think this answer is useful

If you already have a reference to a radio button group, for example:

var myRadio = $("input[name=myRadio]");

Use the filter() function, not find(). (find() is for locating child/descendant elements, whereas filter() searches top-level elements in your selection.)

var checkedValue = myRadio.filter(":checked").val();

Notes: This answer was originally correcting another answer that recommended using find(), which seems to have since been changed. find() could still be useful for the situation where you already had a reference to a container element, but not to the radio buttons, e.g.:

var form = $("#mainForm");
...
var checkedValue = form.find("input[name=myRadio]:checked").val();

The Answer 4

143 people think this answer is useful

This should work:

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

Note the “” usaged around the input:checked and not ” like the Peter J’s solution

The Answer 5

81 people think this answer is useful

You can use the :checked selector along with the radio selector.

 $("form:radio:checked").val();

The Answer 6

61 people think this answer is useful

If you want just the boolean value, i.e. if it’s checked or not try this:

$("#Myradio").is(":checked")

The Answer 7

54 people think this answer is useful

Get all radios:

var radios = jQuery("input[type='radio']");

Filter to get the one thats checked

radios.filter(":checked")

The Answer 8

51 people think this answer is useful

Another option is:

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

The Answer 9

31 people think this answer is useful
$("input:radio:checked").val();

The Answer 10

25 people think this answer is useful

Here’s how I would write the form and handle the getting of the checked radio.

Using a form called myForm:

<form id='myForm'>
    <input type='radio' name='radio1' class='radio1' value='val1' />
    <input type='radio' name='radio1' class='radio1' value='val2' />
    ...
</form>

Get the value from the form:

$('#myForm .radio1:checked').val();

If you’re not posting the form, I would simplify it further by using:

<input type='radio' class='radio1' value='val1' />
<input type='radio' class='radio1' value='val2' />

Then getting the checked value becomes:

    $('.radio1:checked').val();

Having a class name on the input allows me to easily style the inputs…

The Answer 11

25 people think this answer is useful

In my case I have two radio buttons in one form and I wanted to know the status of each button. This below worked for me:

// get radio buttons value
console.log( "radio1: " +  $('input[id=radio1]:checked', '#toggle-form').val() );
console.log( "radio2: " +  $('input[id=radio2]:checked', '#toggle-form').val() );


    
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;</script&gt;
<form id="toggle-form"&gt;
  <div id="radio"&gt;
    <input type="radio" id="radio1" name="radio" checked="checked" /&gt;<label for="radio1"&gt;Plot single</label&gt;
    <input type="radio" id="radio2" name="radio"/&gt;<label for="radio2"&gt;Plot all</label&gt;
  </div&gt;
</form&gt;

The Answer 12

17 people think this answer is useful

In a JSF generated radio button (using <h:selectOneRadio> tag), you can do this:

radiobuttonvalue = jQuery("input[name='form_id\:radiobutton_id']:checked").val();

where selectOneRadio ID is radiobutton_id and form ID is form_id.

Be sure to use name instead id, as indicated, because jQuery uses this attribute (name is generated automatically by JSF resembling control ID).

The Answer 13

16 people think this answer is useful

Also, check if the user does not select anything.

var radioanswer = 'none';
if ($('input[name=myRadio]:checked').val() != null) {           
   radioanswer = $('input[name=myRadio]:checked').val();
}

The Answer 14

15 people think this answer is useful

If you have Multiple radio buttons in single form then

var myRadio1 = $('input[name=radioButtonName1]');
var value1 = myRadio1.filter(':checked').val();

var myRadio2 = $('input[name=radioButtonName2]');
var value2 = myRadio2.filter(':checked').val();

This is working for me.

The Answer 15

15 people think this answer is useful

I wrote a jQuery plugin for setting and getting radio-button values. It also respects the “change” event on them.

(function ($) {

    function changeRadioButton(element, value) {
        var name = $(element).attr("name");
        $("[type=radio][name=" + name + "]:checked").removeAttr("checked");
        $("[type=radio][name=" + name + "][value=" + value + "]").attr("checked", "checked");
        $("[type=radio][name=" + name + "]:checked").change();
    }

    function getRadioButton(element) {
        var name = $(element).attr("name");
        return $("[type=radio][name=" + name + "]:checked").attr("value");
    }

    var originalVal = $.fn.val;
    $.fn.val = function(value) {

        //is it a radio button? treat it differently.
        if($(this).is("[type=radio]")) {

            if (typeof value != 'undefined') {

                //setter
                changeRadioButton(this, value);
                return $(this);

            } else {

                //getter
                return getRadioButton(this);

            }

        } else {

            //it wasn't a radio button - let's call the default val function.
            if (typeof value != 'undefined') {
                return originalVal.call(this, value);
            } else {
                return originalVal.call(this);
            }

        }
    };
})(jQuery);

Put the code anywhere to enable the addin. Then enjoy! It just overrides the default val function without breaking anything.

You can visit this jsFiddle to try it in action, and see how it works.

Fiddle

The Answer 16

13 people think this answer is useful
 $(".Stat").click(function () {
     var rdbVal1 = $("input[name$=S]:checked").val();
 }

The Answer 17

12 people think this answer is useful

This works fine

$('input[type="radio"][class="className"]:checked').val()

Working Demo

The :checked selector works for checkboxes, radio buttons, and select elements. For select elements only, use the :selected selector.

API for :checked Selector

The Answer 18

11 people think this answer is useful

To get the value of the selected radio that uses a class:

$('.class:checked').val()

The Answer 19

10 people think this answer is useful

I use this simple script

$('input[name="myRadio"]').on('change', function() {
  var radioValue = $('input[name="myRadio"]:checked').val();        
  alert(radioValue); 
});

The Answer 20

10 people think this answer is useful

Use this:

value = $('input[name=button-name]:checked').val();

The Answer 21

8 people think this answer is useful

DEMO : https://jsfiddle.net/ipsjolly/xygr065w/

	$(function(){
	    $("#submit").click(function(){      
	        alert($('input:radio:checked').val());
	    });
	 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;</script&gt;
<table&gt;
       <tr&gt;
         <td&gt;Sales Promotion</td&gt;
         <td&gt;<input type="radio" name="q12_3" value="1"&gt;1</td&gt;
         <td&gt;<input type="radio" name="q12_3" value="2"&gt;2</td&gt;
         <td&gt;<input type="radio" name="q12_3" value="3"&gt;3</td&gt;
         <td&gt;<input type="radio" name="q12_3" value="4"&gt;4</td&gt;
         <td&gt;<input type="radio" name="q12_3" value="5"&gt;5</td&gt;
      </tr&gt;
    </table&gt;
<button id="submit"&gt;submit</button&gt;

The Answer 22

6 people think this answer is useful

If you only have 1 set of radio buttons on 1 form, the jQuery code is as simple as this:

$( "input:checked" ).val()

The Answer 23

5 people think this answer is useful

I’ve released a library to help with this. Pulls all possible input values, actually, but also includes which radio button was checked. You can check it out at https://github.com/mazondo/formalizedata

It’ll give you a js object of the answers, so a form like:

<form>
<input type="radio" name"favorite-color" value="blue" checked> Blue
<input type="radio" name="favorite-color" value="red"> Red
</form>

will give you:

$("form").formalizeData()
{
  "favorite-color" : "blue"
}

The Answer 24

5 people think this answer is useful

JQuery to get all the radio buttons in the form and the checked value.

$.each($("input[type='radio']").filter(":checked"), function () {
  console.log("Name:" + this.name);
  console.log("Value:" + $(this).val());
});

The Answer 25

4 people think this answer is useful

To retrieve all radio buttons values in JavaScript array use following jQuery code :

var values = jQuery('input:checkbox:checked.group1').map(function () {
    return this.value;
}).get();

The Answer 26

4 people think this answer is useful

try it-

var radioVal = $("#myform").find("input[type='radio']:checked").val();

console.log(radioVal);

The Answer 27

3 people think this answer is useful

Another way to get it:

 $("#myForm input[type=radio]").on("change",function(){
   if(this.checked) {
    alert(this.value);
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;</script&gt;
<form id="myForm"&gt;
   <span&gt;<input type="radio" name="q12_3" value="1"&gt;1</span&gt;<br&gt;
   <span&gt;<input type="radio" name="q12_3" value="2"&gt;2</span&gt;
</form&gt;

The Answer 28

2 people think this answer is useful
$(function () {
// Someone has clicked one of the radio buttons
var myform= 'form.myform';
$(myform).click(function () {
    var radValue= "";
    $(this).find('input[type=radio]:checked').each(function () {
        radValue= $(this).val();
    });
  })
});

The Answer 29

1 people think this answer is useful

From this question, I came up with an alternate way to access the currently selected input when you’re within a click event for its respective label. The reason why is because the newly selected input isn’t updated until after its label‘s click event.

TL;DR

$('label').click(function() {
  var selected = $('#' + $(this).attr('for')).val();

  ...
});

$(function() {
  // this outright does not work properly as explained above
  $('#reported label').click(function() {
    var query = $('input[name="filter"]:checked').val();
    var time = (new Date()).toString();

    $('.query[data-method="click event"]').html(query + ' at ' + time);
  });

  // this works, but fails to update when same label is clicked consecutively
  $('#reported input[name="filter"]').on('change', function() {
    var query = $('input[name="filter"]:checked').val();
    var time = (new Date()).toString();

    $('.query[data-method="change event"]').html(query + ' at ' + time);
  });

  // here is the solution I came up with
  $('#reported label').click(function() {
    var query = $('#' + $(this).attr('for')).val();
    var time = (new Date()).toString();

    $('.query[data-method="click event with this"]').html(query + ' at ' + time);
  });
});
input[name="filter"] {
  display: none;
}
#reported label {
  background-color: #ccc;
  padding: 5px;
  margin: 5px;
  border-radius: 5px;
  cursor: pointer;
}
.query {
  padding: 5px;
  margin: 5px;
}
.query:before {
  content: "on " attr(data-method)": ";
}
[data-method="click event"] {
  color: red;
}
[data-method="change event"] {
  color: #cc0;
}
[data-method="click event with this"] {
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;</script&gt;
<form id="reported"&gt;
  <input type="radio" name="filter" id="question" value="questions" checked="checked"&gt;
  <label for="question"&gt;Questions</label&gt;

  <input type="radio" name="filter" id="answer" value="answers"&gt;
  <label for="answer"&gt;Answers</label&gt;

  <input type="radio" name="filter" id="comment" value="comments"&gt;
  <label for="comment"&gt;Comments</label&gt;

  <input type="radio" name="filter" id="user" value="users"&gt;
  <label for="user"&gt;Users</label&gt;

  <input type="radio" name="filter" id="company" value="companies"&gt;
  <label for="company"&gt;Companies</label&gt;

  <div class="query" data-method="click event"&gt;</div&gt;
  <div class="query" data-method="change event"&gt;</div&gt;
  <div class="query" data-method="click event with this"&gt;</div&gt;
</form&gt;

The Answer 30

1 people think this answer is useful

What I needed to do was simplify C# code, that is do as much as possible in the front end JavaScript. I’m using a fieldset container because I’m working in DNN and it has its own form. So I can’t add a form.

I need to test which text box out of 3 is being used and if it is, what’s the type of search? Starts with the value, Contains the value, Exact Match of the value.

HTML:

<fieldset id="fsPartNum" class="form-inline">
<div class="form-group">
    <label for="txtPartNumber">Part Number:</label>
    <input type="text" id="txtPartNumber" class="input-margin-pn" />
</div>
<div class="form-group">
    <label for="radPNStartsWith">Starts With: </label>
    <input type="radio" id="radPNStartsWith" name="partNumber" checked  value="StartsWith"/>
</div>
<div class="form-group">
    <label for="radPNContains">Contains: </label>
    <input type="radio" id="radPNContains" name="partNumber" value="Contains" />
</div>
<div class="form-group">
    <label for="radPNExactMatch">Exact Match: </label>
    <input type="radio" id="radPNExactMatch" name="partNumber" value="ExactMatch" />
</div>

And my JavaScript is:

        alert($('input[name=partNumber]:checked', '#fsPartNum').val()); 
    if(txtPartNumber.val() !== ''){
        message = 'Customer Part Number';
    }
    else if(txtCommercialPartNumber.val() !== ''){

    }
    else if(txtDescription.val() !== ''){

    }

Just saying any containing tag with an ID can be used. For DNNers, this is good to know. The end goal here is pass to the mid-level code what is needed to start a parts search in SQL Server.

This way I don’t have to copy the much more complicated previous C# code also. The heavy lifting is being done right here.

I had to look a bit for this and then tinker with it to get it to work. So for other DNNers, hopefully this is easy to find.

Add a Comment