How can I know which radio button is selected via jQuery?
Asked Answered
F

39

3066

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?

Fairground answered 27/2, 2009 at 19:53 Comment(0)
R
4297

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">
  <fieldset>
    <legend>Choose radioName</legend>
    <label><input type="radio" name="radioName" value="1" /> 1</label> <br />
    <label><input type="radio" name="radioName" value="2" /> 2</label> <br />
    <label><input type="radio" name="radioName" value="3" /> 3</label> <br />
  </fieldset>
</form>
Rosamariarosamond answered 27/2, 2009 at 19:58 Comment(6)
Just going to add this because it might help someone. If the name of the radio has brackets like radioName[0] (sometimes used in Wordpress), you will want to use quotes around the name like input[name='radioName[0]']:checkedAmara
Just noting, in the onChange method example, you can also use this.value instead of $('input[name=radioName]:checked', '#myForm').val() :)Valarievalda
For a non-jquery version, see here: jsfiddle.net/2y76vp1eCain
@ ZeroNine, that's also the case in Symfony framework that I use.Rations
This is a great answer. I'd like to confirm something: if a class of "radio" is assigned to the radio button, does something like $(".radio:checked", "#myForm").val() work as well? And what about $("#myForm .radio:checked").val()?Davison
@AngelUmeh that's right!Rosamariarosamond
T
468

Use this..

$("#myform input[type='radio']:checked").val();
Tebet answered 7/1, 2010 at 0:45 Comment(0)
I
349

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();
Incubation answered 9/2, 2011 at 18:25 Comment(0)
F
160

This should work:

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

Note the "" usaged around the input:checked and not '' like the Peter J's solution

Faithless answered 30/3, 2011 at 22:29 Comment(1)
Why does this returns me "on" instead of the value of the selected radio button?Meritocracy
H
87

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

 $("form:radio:checked").val();
Hocuspocus answered 27/2, 2009 at 20:0 Comment(1)
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.Exsanguine
W
79

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

$("#Myradio").is(":checked")
Woodbury answered 30/8, 2013 at 20:27 Comment(0)
F
61

Get all radios:

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

Filter to get the one thats checked

radios.filter(":checked")
Frontage answered 1/9, 2011 at 17:55 Comment(0)
S
58

Another option is:

$('input[name=radioName]:checked').val()
Sudd answered 21/9, 2011 at 19:35 Comment(1)
The ":radio" part isn't necessary here.Incubation
S
34
$("input:radio:checked").val();
Sander answered 16/10, 2010 at 20:20 Comment(0)
J
28

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>
Jolly answered 2/8, 2012 at 17:9 Comment(1)
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.Porcelain
M
27

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

Moderate answered 21/9, 2012 at 16:19 Comment(0)
T
22

try this one. it worked for me

$('input[type="radio"][name="name"]:checked').val();
Townes answered 28/9, 2020 at 11:48 Comment(0)
H
19

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

Hallel answered 29/9, 2010 at 19:6 Comment(0)
S
18

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();
}
Sri answered 15/11, 2011 at 16:4 Comment(0)
L
18

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.

Leucoderma answered 7/6, 2012 at 4:45 Comment(0)
P
17

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

Propend answered 17/4, 2013 at 9:58 Comment(0)
S
15
 $(".Stat").click(function () {
     var rdbVal1 = $("input[name$=S]:checked").val();
 }
Somniloquy answered 17/7, 2012 at 12:1 Comment(0)
M
15

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

Micheal answered 14/2, 2015 at 11:41 Comment(0)
W
13

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

$('.class:checked').val()
Weswesa answered 11/1, 2013 at 18:5 Comment(0)
C
12

I use this simple script

$('input[name="myRadio"]').on('change', function() {
  var radioValue = $('input[name="myRadio"]:checked').val();        
  alert(radioValue); 
});
Climacteric answered 19/10, 2014 at 17:34 Comment(1)
Use the click event rather than the change event if you want it to work in all browsersIncubation
D
11

Use this:

value = $('input[name=button-name]:checked').val();
Datum answered 10/8, 2013 at 18:22 Comment(0)
R
9

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>
Reeva answered 1/8, 2017 at 6:9 Comment(0)
U
7

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

$( "input:checked" ).val()
Unipersonal answered 12/8, 2013 at 2:13 Comment(0)
B
6

Using $('input[name="radioName"]').filter(":checked").val(); is the best way for me.

Tested, this works

Form

<form id="myForm">
  <input type="radio" name="radioName" value="Option1"> Option1
  <input type="radio" name="radioName" value="Option2" checked> Option2
  <input type="radio" name="radioName" value="Option3"> Option3
</form>

Jquery

$(document).ready(function() {
  $('input[name="radioName"]').on('change', function() {
     const val = $(this).filter(":checked").val();
     alert(val);
  })

  // First load check
  const val = $('input[name="radioName"]').filter(":checked").val();
  alert(val);
});

Example here: https://codepen.io/abinhho/pen/mdLrqbX

Bestial answered 13/9, 2022 at 4:24 Comment(0)
M
5

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"
}
Malefic answered 23/1, 2014 at 6:40 Comment(0)
L
5

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());
});
Lamellirostral answered 7/11, 2018 at 20:27 Comment(0)
B
4

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();
Bipropellant answered 3/9, 2013 at 3:25 Comment(1)
Radio buttons are not the same as checkboxes. This example uses checkboxes.Incubation
S
4

try it-

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

console.log(radioVal);
Shizukoshizuoka answered 10/7, 2017 at 12:21 Comment(0)
J
4

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>
Jamilla answered 3/10, 2017 at 12:56 Comment(0)
S
2

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>
Sabaean answered 15/1, 2016 at 17:31 Comment(0)
G
2
$(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();
    });
  })
});
Golf answered 4/5, 2017 at 21:26 Comment(0)
O
2

Try

myForm.myOption.value

function check() {
  console.log( myForm.myOption.value );
}
<form id="myForm">
  <input type="radio" name="myOption" value="1"> 1 <br>
  <input type="radio" name="myOption" value="2"> 2 <br>
  <input type="radio" name="myOption" value="3"> 3 <br>
</form>
<button onclick="check()">check</button>
Overexpose answered 10/1, 2020 at 9:22 Comment(0)
A
2

This solution does not require jQuery.

const RADIO_NAME = "radioName";
const radios = Array.from(document.getElementsByName(RADIO_NAME));
const checkedRadio = radios.filter(e=>e.checked);

This uses jQuery:

const radios = Array.from($(`[name=${RADIO_NAME}`));
const checkedRadio = radios.filter(e=>e.checked);

jQuery adds an extra layer of abstraction that isn't needed here.

You could also use:

const radios = Array.from(document.querySelectorAll(`[name=${RADIO_NAME}`));
const checkedRadio = radios.filter(e=>e.checked)[0];

But getElementsByName is simple and clear enough.

Abstractionism answered 2/1, 2021 at 21:5 Comment(1)
Your vanilla solution seems a bit bloated. One could use document.querySelector('[name=radioName]:checked') instead. And document.querySelectorAll(':checked') for all the checked radios in the document.Plascencia
C
1

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.

Classmate answered 4/9, 2017 at 15:41 Comment(0)
U
1

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>
Ultra answered 18/7, 2018 at 10:49 Comment(0)
S
1

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>
Sequela answered 26/1, 2019 at 14:5 Comment(0)
H
1

**Please try below example to check which radio button in selected **

<script>
    $('#form1 input').on('change', function() {
       alert($('input[name=age]:checked', '#form1 ').val()); 
    });
</script>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
    <form id="form1">
      <input type="radio" name="age" value="18" /> 18 <br />
      <input type="radio" name="age" value="20" /> 20 <br />
      <input type="radio" name="age" value="22" /> 22 <br />
    </form>
Hi answered 29/5, 2019 at 4:59 Comment(0)
P
1

Along with the CSS selector :checked, you can also use the prop function (as of jQuery 1.6). I can't remember what project I was working on where simply using $('#something').is(':checked') only worked sometimes, and I resorted to also using $('#something').prop('checked') worked when it failed, but it led me to using both.

In my code snippet below, I've written two helper functions, is_checked and get_group_value. The function is_checked returns a boolean true/false value; true if the input passed in the parameter is checked (also checks with the prop() function) or false if it's not checked. The function get_group_value takes the name of the radio inputs and returns the value of the one that is checked, or an empty string if none are checked. These helper functions will also work with checkboxes, not just radio buttons.

Since the question did not define when they're retrieving the value(s), I've written a few listeners for four (3) different scenarios: when interacting with any radio button, when submitting the form, and when clicking one of these hard-coded buttons to do a one-time retrieval of the value of the group.

Please note that I'm using "click" to identify when the user interacts with the radio input element because "change" will never get triggered since the "value" attribute doesn't get changed when it's checked or not. I use this for checkboxes as well as radio buttons.

function is_checked(input) {
  var $input = $(input);
  return $input.is(':checked') || $input.prop('checked'); //Returns a boolean value. True if checked, false if not.
}
function get_group_value(group_name) {
  var $inputs = $('[name="' + group_name + '"]:checked');
  if ($inputs.length) { return $inputs.first().val(); } //If it exists, return the value of the first one found
  return ''; //If it doesn't exist, return nothing
}
$('form').on('submit', function(e) {
  e.preventDefault();
  var $form = $(this), results = {};
  $form.find('input[type=radio]').each(function() {
    var $input = $(this);
    if (is_checked(this)) {
      results[$input.attr('name')] = $input.val();
    }
  });
  console.info('Form Results', results);
});
$('form input[type=radio]').on('click', function(e) {
  var group_name = $(this).attr('name');
  console.info('Radio Button Click', group_name, get_group_value(group_name));
});
$('button.radio-button').on('click', function(e) {
  var group_name = $(this).attr('id');
  console.info('Button Click', group_name, get_group_value(group_name));
});
.my-test {
  background: #ffffff;
  color: #000000;
  padding: 16px;
}

form {
  padding: 8px;
  border: 1px solid #999999;
}

fieldset {
  border: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="my-test">
  <form>
    Group 1
    <fieldset>
      <label><input type="radio" name="example-1" value="Foo" required />Foo</label>
      <label><input type="radio" name="example-1" value="Bar" required />Bar</label>
    </fieldset>
    Group 2
    <fieldset>
      <label><input type="radio" name="example-2" value="Banana" required />Banana</label>
      <label><input type="radio" name="example-2" value="Apple" required />Apple</label>
    </fieldset>
    <button type="submit">Submit</button>
  </form>
  <p>Press this button to just get the value of the first group: <button class="radio-button" id="example-1">Foo or Bar?</button></p>
  <p>Press this button to just get the value of the second group: <button class="radio-button" id="example-2">Banana or Apple?</button></p>
</div>
Postilion answered 13/4, 2020 at 19:41 Comment(0)
R
0

jQuery plugin for setting and getting radio-button values. It also respects the "change" event on them.

 <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>
    <script type="text/javascript">
    $( document ).ready(function() {
     //Get all radios:
     var radios = jQuery("input[type='radio']");
     checked_radios=radios.filter(":checked");
for(i=0;i<checked_radios.length;i++)
{
   console.log(checked_radios[i]);
}

    });
    </script>

or another way

<script type="text/javascript">
$( document ).ready(function() {
  //Get all radios:
  checked_radios=jQuery('input[name=radio]:checked').val(); 
for(i=0;i<checked_radios.length;i++)
{
   console.log(checked_radios[i]);
}

});
</script>
Ruberta answered 27/2, 2009 at 19:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.