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

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?

This question is related to javascript jquery html jquery-selectors radio-button

The answer is


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


Use this:

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

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.

_x000D_
_x000D_
function is_checked(input) {_x000D_
  var $input = $(input);_x000D_
  return $input.is(':checked') || $input.prop('checked'); //Returns a boolean value. True if checked, false if not._x000D_
}_x000D_
function get_group_value(group_name) {_x000D_
  var $inputs = $('[name="' + group_name + '"]:checked');_x000D_
  if ($inputs.length) { return $inputs.first().val(); } //If it exists, return the value of the first one found_x000D_
  return ''; //If it doesn't exist, return nothing_x000D_
}_x000D_
$('form').on('submit', function(e) {_x000D_
  e.preventDefault();_x000D_
  var $form = $(this), results = {};_x000D_
  $form.find('input[type=radio]').each(function() {_x000D_
    var $input = $(this);_x000D_
    if (is_checked(this)) {_x000D_
      results[$input.attr('name')] = $input.val();_x000D_
    }_x000D_
  });_x000D_
  console.info('Form Results', results);_x000D_
});_x000D_
$('form input[type=radio]').on('click', function(e) {_x000D_
  var group_name = $(this).attr('name');_x000D_
  console.info('Radio Button Click', group_name, get_group_value(group_name));_x000D_
});_x000D_
$('button.radio-button').on('click', function(e) {_x000D_
  var group_name = $(this).attr('id');_x000D_
  console.info('Button Click', group_name, get_group_value(group_name));_x000D_
});
_x000D_
.my-test {_x000D_
  background: #ffffff;_x000D_
  color: #000000;_x000D_
  padding: 16px;_x000D_
}_x000D_
_x000D_
form {_x000D_
  padding: 8px;_x000D_
  border: 1px solid #999999;_x000D_
}_x000D_
_x000D_
fieldset {_x000D_
  border: none;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="my-test">_x000D_
  <form>_x000D_
    Group 1_x000D_
    <fieldset>_x000D_
      <label><input type="radio" name="example-1" value="Foo" required />Foo</label>_x000D_
      <label><input type="radio" name="example-1" value="Bar" required />Bar</label>_x000D_
    </fieldset>_x000D_
    Group 2_x000D_
    <fieldset>_x000D_
      <label><input type="radio" name="example-2" value="Banana" required />Banana</label>_x000D_
      <label><input type="radio" name="example-2" value="Apple" required />Apple</label>_x000D_
    </fieldset>_x000D_
    <button type="submit">Submit</button>_x000D_
  </form>_x000D_
  <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>_x000D_
  <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>_x000D_
</div>
_x000D_
_x000D_
_x000D_


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

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

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

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>

try it-

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

console.log(radioVal);

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


try this one. it worked for me $('input[type="radio"][name="name"]:checked').val();


Another option is:

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

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

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

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


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

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

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

  ...
});

_x000D_
_x000D_
$(function() {_x000D_
  // this outright does not work properly as explained above_x000D_
  $('#reported label').click(function() {_x000D_
    var query = $('input[name="filter"]:checked').val();_x000D_
    var time = (new Date()).toString();_x000D_
_x000D_
    $('.query[data-method="click event"]').html(query + ' at ' + time);_x000D_
  });_x000D_
_x000D_
  // this works, but fails to update when same label is clicked consecutively_x000D_
  $('#reported input[name="filter"]').on('change', function() {_x000D_
    var query = $('input[name="filter"]:checked').val();_x000D_
    var time = (new Date()).toString();_x000D_
_x000D_
    $('.query[data-method="change event"]').html(query + ' at ' + time);_x000D_
  });_x000D_
_x000D_
  // here is the solution I came up with_x000D_
  $('#reported label').click(function() {_x000D_
    var query = $('#' + $(this).attr('for')).val();_x000D_
    var time = (new Date()).toString();_x000D_
_x000D_
    $('.query[data-method="click event with this"]').html(query + ' at ' + time);_x000D_
  });_x000D_
});
_x000D_
input[name="filter"] {_x000D_
  display: none;_x000D_
}_x000D_
#reported label {_x000D_
  background-color: #ccc;_x000D_
  padding: 5px;_x000D_
  margin: 5px;_x000D_
  border-radius: 5px;_x000D_
  cursor: pointer;_x000D_
}_x000D_
.query {_x000D_
  padding: 5px;_x000D_
  margin: 5px;_x000D_
}_x000D_
.query:before {_x000D_
  content: "on " attr(data-method)": ";_x000D_
}_x000D_
[data-method="click event"] {_x000D_
  color: red;_x000D_
}_x000D_
[data-method="change event"] {_x000D_
  color: #cc0;_x000D_
}_x000D_
[data-method="click event with this"] {_x000D_
  color: green;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form id="reported">_x000D_
  <input type="radio" name="filter" id="question" value="questions" checked="checked">_x000D_
  <label for="question">Questions</label>_x000D_
_x000D_
  <input type="radio" name="filter" id="answer" value="answers">_x000D_
  <label for="answer">Answers</label>_x000D_
_x000D_
  <input type="radio" name="filter" id="comment" value="comments">_x000D_
  <label for="comment">Comments</label>_x000D_
_x000D_
  <input type="radio" name="filter" id="user" value="users">_x000D_
  <label for="user">Users</label>_x000D_
_x000D_
  <input type="radio" name="filter" id="company" value="companies">_x000D_
  <label for="company">Companies</label>_x000D_
_x000D_
  <div class="query" data-method="click event"></div>_x000D_
  <div class="query" data-method="change event"></div>_x000D_
  <div class="query" data-method="click event with this"></div>_x000D_
</form>
_x000D_
_x000D_
_x000D_


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

Another way to get it:

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


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

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

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

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

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.


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


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:

_x000D_
_x000D_
// get radio buttons value_x000D_
console.log( "radio1: " +  $('input[id=radio1]:checked', '#toggle-form').val() );_x000D_
console.log( "radio2: " +  $('input[id=radio2]:checked', '#toggle-form').val() );_x000D_
_x000D_
_x000D_
    
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form id="toggle-form">_x000D_
  <div id="radio">_x000D_
    <input type="radio" id="radio1" name="radio" checked="checked" /><label for="radio1">Plot single</label>_x000D_
    <input type="radio" id="radio2" name="radio"/><label for="radio2">Plot all</label>_x000D_
  </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_


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.


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

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

You need access with the :checked selector:

Check this doc:

a example:

_x000D_
_x000D_
$('input[name=radioName]:checked', '#myForm').val()_x000D_
$('#myForm input').on('change', function() {_x000D_
 $('#val').text($('input[name=radioName]:checked', '#myForm').val());_x000D_
});
_x000D_
#val {_x000D_
  color: #EB0054;_x000D_
  font-size: 1.5em;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<h3>Radio value: <span id='val'><span></h3>_x000D_
<form id="myForm">_x000D_
  <input type="radio" name="radioName" value="a"> a <br>_x000D_
  <input type="radio" name="radioName" value="b"> b <br>_x000D_
  <input type="radio" name="radioName" value="c"> c <br>_x000D_
</form>
_x000D_
_x000D_
_x000D_


Use this..

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

This should work:

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

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


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>

I use this simple script

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

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

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.


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

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


Try

myForm.myOption.value

_x000D_
_x000D_
function check() {_x000D_
  console.log( myForm.myOption.value );_x000D_
}
_x000D_
<form id="myForm">_x000D_
  <input type="radio" name="myOption" value="1"> 1 <br>_x000D_
  <input type="radio" name="myOption" value="2"> 2 <br>_x000D_
  <input type="radio" name="myOption" value="3"> 3 <br>_x000D_
</form>_x000D_
<button onclick="check()">check</button>
_x000D_
_x000D_
_x000D_


How about this?

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

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


Get all radios:

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

Filter to get the one thats checked

radios.filter(":checked")

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

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to jquery-selectors

Why is my JQuery selector returning a n.fn.init[0], and what is it? How to use placeholder as default value in select2 framework Access the css ":after" selector with jQuery jQuery: using a variable as a selector Check if any ancestor has a class using jQuery jQuery selector first td of each row Select element by exact match of its content jQuery selector to get form by name jQuery : select all element with custom attribute Set select option 'selected', by value

Examples related to radio-button

Angular 4 default radio button checked by default Angular2 - Radio Button Binding Detect if a Form Control option button is selected in VBA How to create radio buttons and checkbox in swift (iOS)? How to check if a radiobutton is checked in a radiogroup in Android? Radio Buttons ng-checked with ng-model Multiple radio button groups in MVC 4 Razor Show div when radio button selected Check a radio button with javascript Bootstrap radio button "checked" flag