By juan


2009-02-27 19:53:27 8 Comments

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?

30 comments

@Alireza 2019-01-26 14:05:43

How about this?

Using change and get the value of radio type is checked...

$('#my-radio-form').on('change', function() {
  console.log($('[type="radio"]:checked').val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<form id="my-radio-form">
  <input type="radio" name="input-radio" value="a" />a
  <input type="radio" name="input-radio" value="b" />b
  <input type="radio" name="input-radio" value="c" />c
  <input type="radio" name="input-radio" value="d" />d
</form>

@Iyyappan Amirthalingam 2018-11-07 20:27:20

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

@RedDragon 2011-09-21 19:35:22

Another option is:

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

@Matt Browne 2015-01-31 13:13:46

The ":radio" part isn't necessary here.

@fitorec 2018-07-18 10:49:42

You need access with the :checked selector:

Check this doc:

a example:

$('input[name=radioName]:checked', '#myForm').val()
$('#myForm input').on('change', function() {
	$('#val').text($('input[name=radioName]:checked', '#myForm').val());
});
#val {
  color: #EB0054;
  font-size: 1.5em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h3>Radio value: <span id='val'><span></h3>
<form id="myForm">
  <input type="radio" name="radioName" value="a"> a <br>
  <input type="radio" name="radioName" value="b"> b <br>
  <input type="radio" name="radioName" value="c"> c <br>
</form>

@sandeep kumar 2018-07-04 08:31:58

You can call Function onChange()

  <input type="radio" name="radioName" value="1" onchange="radio_changed($(this).val())" /> 1 <br />
  <input type="radio" name="radioName" value="2" onchange="radio_changed($(this).val())"  /> 2 <br />
  <input type="radio" name="radioName" value="3"  onchange="radio_changed($(this).val())" /> 3 <br />

<script>
function radio_changed(val){
    alert(val);
}
</script>

@Matt Browne 2011-02-09 18:25:30

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

@Matt Browne 2012-04-03 00:06:20

I just wanted to add, for the sake of clarity, that find() actually searches all descendent elements (which match the given selector). If you only want direct children, use children().

@Peter J 2009-02-27 19:58:39

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"></script>
<form id="myForm">
  <input type="radio" name="radioName" value="1" /> 1 <br />
  <input type="radio" name="radioName" value="2" /> 2 <br />
  <input type="radio" name="radioName" value="3" /> 3 <br />
</form>

@juan 2009-02-27 20:02:21

I ended up using this: $('form input[type=radio]:checked')

@Sophie Alpert 2011-07-12 17:30:21

@PeterJ: Why'd you use two arguments instead of simply '#myform input[name=radioName]:checked'?

@Peter J 2011-07-12 18:03:38

jQuery performs best when scoped correctly, and selecting by ID is always the highest performing selector. The two-argument method is simply another way of doing it.

@Bakaburg 2012-08-05 15:28:02

Why not :radio:checked?

@Peter J 2012-08-09 19:50:40

For best performance, the documentation recommends not using the :radio selector. api.jquery.com/radio-selector

@Meetai.com 2012-10-18 15:32:09

Alternate: $('.className:checked');

@pspahn 2012-12-18 22:00:04

Using this returns strange results (other checked radio inputs on same page) - jQuery('input[name=radio_array[option_a]]:checked') - I had to scope further down to get it working - can we not use array based names with this?

@Matt Browne 2013-02-28 13:30:54

@pspahn You'd need to use quotes around the name in that case, i.e. name="radio_array[option_a]" so jQuery can parse it properly

@Matt Browne 2013-02-28 13:57:33

@PeterJ It's true that it's more performant with older browsers but with browsers that support querySelectorAll, using $('#myForm input[name=radioName]:checked') should be faster, since jQuery uses querySelectorAll internally when it can, and it has to rewrite the query to put '#myForm ' (actually [id=myForm] but that's an implementation detail) in front of the query you give it anyway. If browsers fix querySelectorAll to work properly on element-rooted queries in the future, this may no longer be true in a future version of jQuery.

@Todd 2014-01-07 14:10:39

Strangely, this is working for me until I change the radio button a few times... then it breaks. I'm using, for example, $('input[name=medexam]:checked').val();. This works when the element has checked but not when the script/browser adds checked="checked". Any fix for this?

@Peter J 2014-01-09 22:22:54

I'm not seeing that behavior using the fiddle in my answer, on Chrome. Feel free to post a fiddle here and I'll look at it, but you might have better luck posting an additional question that specifically looks at the issue you're seeing.

@chris 2014-01-15 13:34:24

$('#anyId input[type=radio]:checked').val() worked perfect for me

@Steve Van Opstal 2015-04-05 19:18:26

Instead of $('#myform input[type=radio]:checked').val() you can use $('#myform input:radio:checked').val()

@rushil 2016-09-29 12:14:29

While using $('form input[type=radio]:checked') there is possibility that there may be more than one radio buttons. So to avoid conflicts using id , or radio name as a second selector is a good practice

@Code Spy 2017-08-01 06:09:58

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"></script>
<table>
       <tr>
         <td>Sales Promotion</td>
         <td><input type="radio" name="q12_3" value="1">1</td>
         <td><input type="radio" name="q12_3" value="2">2</td>
         <td><input type="radio" name="q12_3" value="3">3</td>
         <td><input type="radio" name="q12_3" value="4">4</td>
         <td><input type="radio" name="q12_3" value="5">5</td>
      </tr>
    </table>
<button id="submit">submit</button>

@rmbianchi 2012-08-02 17:09:49

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"></script>
<form id="toggle-form">
  <div id="radio">
    <input type="radio" id="radio1" name="radio" checked="checked" /><label for="radio1">Plot single</label>
    <input type="radio" id="radio2" name="radio"/><label for="radio2">Plot all</label>
  </div>
</form>

@Dementic 2014-10-03 11:02:44

What do you mean the status of each button? radio buttons with the same name allows only one to be checked, therefor, if you get the checked one, the rest are unchecked.

@Mehdi Bouzidi 2017-10-03 12:56:52

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"></script>
<form id="myForm">
   <span><input type="radio" name="q12_3" value="1">1</span><br>
   <span><input type="radio" name="q12_3" value="2">2</span>
</form>

@user1585204 2017-09-04 15:41:35

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.

@Gautam Rai 2017-07-10 12:21:21

try it-

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

console.log(radioVal);

@JoshYates1980 2017-05-04 21:26:41

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

@Nilesh 2013-09-03 03:25:23

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

@Matt Browne 2015-01-31 13:20:24

Radio buttons are not the same as checkboxes. This example uses checkboxes.

@Ryan 2014-01-23 06:40:07

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"
}

@Patrick Roberts 2016-01-15 17:31:18

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"></script>
<form id="reported">
  <input type="radio" name="filter" id="question" value="questions" checked="checked">
  <label for="question">Questions</label>

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

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

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

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

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

@Alex V 2011-09-01 17:55:05

Get all radios:

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

Filter to get the one thats checked

radios.filter(":checked")

@Manoj 2015-02-14 11:41:37

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

@jeswin 2013-08-10 18:22:13

Use this:

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

@Lafif Astahdziq 2014-10-19 17:34:09

I use this simple script

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

@Matt Browne 2015-01-31 13:22:39

Use the click event rather than the change event if you want it to work in all browsers

@Mathias Lykkegaard Lorenzen 2013-04-17 09:58:49

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

@Juan 2013-08-30 20:27:20

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

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

@Randy Greencorn 2013-08-12 02:13:15

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

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

@Rodrigo Dias 2013-01-11 18:05:37

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

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

@Darin Peterson 2012-09-21 16:19:38

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

@Swadesh Bhattacharya 2012-07-17 12:01:46

 $(".Stat").click(function () {
     var rdbVal1 = $("input[name$=S]:checked").val();
 }

@Ramesh 2012-06-07 04:45:50

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.

@Phillip Senn 2010-10-16 20:20:16

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

@tvanfosson 2009-02-27 20:00:25

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

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

@J.Money 2012-12-05 01:54:02

This looks nice, however, the jQuery documentation recommends using [type=radio] rather than :radio for better performance. It is a tradeoff between readability and performance. I normally take readability over performance on such trivial matters, but in this case I think [type=radio] is actually clearer. So in this case it would look like $("form input[type=radio]:checked").val(). Still a valid answer though.

@Mark 2011-11-15 16:04:02

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

Related Questions

Sponsored Content

34 Answered Questions

[SOLVED] How do I return the response from an asynchronous call?

53 Answered Questions

[SOLVED] How do I check if an element is hidden in jQuery?

21 Answered Questions

[SOLVED] jQuery get specific option tag text

31 Answered Questions

73 Answered Questions

[SOLVED] How can I get query string values in JavaScript?

60 Answered Questions

[SOLVED] How to check whether a checkbox is checked in jQuery?

32 Answered Questions

[SOLVED] How can I upload files asynchronously?

73 Answered Questions

[SOLVED] How can I convert a string to boolean in JavaScript?

  • 2008-11-05 00:13:08
  • Kevin
  • 1617240 View
  • 2146 Score
  • 73 Answer
  • Tags:   javascript

11 Answered Questions

16 Answered Questions

[SOLVED] How to get the children of the $(this) selector?

Sponsored Content