[javascript] How can I check whether a radio button is selected with JavaScript?

I have two radio buttons within an HTML form. A dialog box appears when one of the fields is null. How can I check whether a radio button is selected?

This question is related to javascript radio-button

The answer is


Just trying to improve on Russ Cam's solution with some CSS selector sugar thrown in with the vanilla JavaScript.

var radios = document.querySelectorAll('input[type="radio"]:checked');
var value = radios.length>0? radios[0].value: null;

No real need for jQuery here, querySelectorAll is widely supported enough now.

Edit: fixed a bug with the css selector, I've included the quotes, although you can omit them, in some cases you can't so it's better to leave them in.


Here is the solution which is expanded upon to not go ahead with submission and send an alert if the radio buttons are not checked. Of course this would mean you have to have them unchecked to begin with!

if(document.getElementById('radio1').checked) {
} else if(document.getElementById('radio2').checked) {
} else {
  alert ("You must select a button");
  return false;
}

Just remember to set the id ('radio1','radio2' or whatever you called it) in the form for each of the radio buttons or the script will not work.


Let's pretend you have HTML like this

<input type="radio" name="gender" id="gender_Male" value="Male" />
<input type="radio" name="gender" id="gender_Female" value="Female" />

For client-side validation, here's some Javascript to check which one is selected:

if(document.getElementById('gender_Male').checked) {
  //Male radio button is checked
}else if(document.getElementById('gender_Female').checked) {
  //Female radio button is checked
}

The above could be made more efficient depending on the exact nature of your markup but that should be enough to get you started.


If you're just looking to see if any radio button is selected anywhere on the page, PrototypeJS makes it very easy.

Here's a function that will return true if at least one radio button is selected somewhere on the page. Again, this might need to be tweaked depending on your specific HTML.

function atLeastOneRadio() {
    return ($('input[type=radio]:checked').size() > 0);
}

For server-side validation (remember, you can't depend entirely on Javascript for validation!), it would depend on your language of choice, but you'd but checking the gender value of the request string.


With mootools (http://mootools.net/docs/core/Element/Element)

html:

<input type="radio" name="radiosname" value="1" />
<input type="radio" name="radiosname" value="2" id="radiowithval2"/>
<input type="radio" name="radiosname" value="3" />

js:

// Check if second radio is selected (by id)
if ($('radiowithval2').get("checked"))

// Check if third radio is selected (by name and value)
if ($$('input[name=radiosname][value=3]:checked').length == 1)


// Check if something in radio group is choosen
if ($$('input[name=radiosname]:checked').length > 0)


// Set second button selected (by id)
$("radiowithval2").set("checked", true)

Return all checked element in the radio button

  Array.from(document.getElementsByClassName("className")).filter(x=>x['checked']);

Try

[...myForm.sex].filter(r=>r.checked)[0].value

_x000D_
_x000D_
function check() {
  let v= ([...myForm.sex].filter(r=>r.checked)[0] || {}).value ;
  console.log(v);
}
_x000D_
<form id="myForm">
  <input name="sex" type="radio" value="men"> Men
  <input name="sex" type="radio" value="woman"> Woman
</form>
<br><button onClick="check()">Check</button>
_x000D_
_x000D_
_x000D_


I used spread operator and some to check least one element in the array passes the test.

I share for whom concern.

_x000D_
_x000D_
var checked = [...document.getElementsByName("gender")].some(c=>c.checked);_x000D_
console.log(checked);
_x000D_
<input type="radio" name="gender" checked value="Male" />_x000D_
<input type="radio" name="gender"  value="Female" / >
_x000D_
_x000D_
_x000D_


The form

<form name="teenageMutant">
  <input type="radio" name="ninjaTurtles"/>
</form>

The script

if(!document.teenageMutant.ninjaTurtles.checked){
  alert('get down');
}

The fiddle: http://jsfiddle.net/PNpUS/


This would be valid for radio buttons sharing the same name, no JQuery needed.

var x = Array.prototype.filter.call(document.getElementsByName('checkThing'), function(x) { return x.checked })[0];

If we are talking about checkboxes and we want a list with the checkboxes checked sharing a name:

var x = Array.prototype.filter.call(document.getElementsByName('checkThing'), function(x) { return x.checked });

This is also working, avoiding to call for an element id but calling it using as an array element.

The following code is based on the fact that an array, named as the radiobuttons group, is composed by radiobuttons elements in the same order as they where declared in the html document:

if(!document.yourformname.yourradioname[0].checked 
   && !document.yourformname.yourradioname[1].checked){
    alert('is this working for all?');
    return false;
}

This code will alert the selected radio button when the form is submitted. It used jQuery to get the selected value.

_x000D_
_x000D_
$("form").submit(function(e) {_x000D_
  e.preventDefault();_x000D_
  $this = $(this);_x000D_
_x000D_
  var value = $this.find('input:radio[name=COLOR]:checked').val();_x000D_
  alert(value);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form>_x000D_
  <input name="COLOR" id="Rojo" type="radio" value="red">_x000D_
  <input name="COLOR" id="Azul" type="radio" value="blue">_x000D_
  <input name="COLOR" id="Amarillo" type="radio" value="yellow">_x000D_
  <br>_x000D_
  <input type="submit" value="Submit">_x000D_
</form>
_x000D_
_x000D_
_x000D_


just a lil bit modification to Mark Biek ;

HTML CODE

<form name="frm1" action="" method="post">
  <input type="radio" name="gender" id="gender_Male" value="Male" />
  <input type="radio" name="gender" id="gender_Female" value="Female" / >
  <input type="button" value="test"  onclick="check1();"/>
</form>

and Javascript code to check if radio button is selected

<script type="text/javascript">
    function check1() {            
        var radio_check_val = "";
        for (i = 0; i < document.getElementsByName('gender').length; i++) {
            if (document.getElementsByName('gender')[i].checked) {
                alert("this radio button was clicked: " + document.getElementsByName('gender')[i].value);
                radio_check_val = document.getElementsByName('gender')[i].value;        
            }        
        }
        if (radio_check_val === "")
        {
            alert("please select radio button");
        }        
    }
</script>

The scripts in this page helped me come up with the script below, which I think is more complete and universal. Basically it will validate any number of radio buttons in a form, meaning that it will make sure that a radio option has been selected for each one of the different radio groups within the form. e.g in the test form below:

   <form id="FormID">

    Yes <input type="radio" name="test1" value="Yes">
    No <input type="radio" name="test1" value="No">

    <br><br>

    Yes <input type="radio" name="test2" value="Yes">
    No <input type="radio" name="test2" value="No">

   <input type="submit" onclick="return RadioValidator();">

The RadioValidator script will make sure that an answer has been given for both 'test1' and 'test2' before it submits. You can have as many radio groups in the form, and it will ignore any other form elements. All missing radio answers will show inside a single alert popup. Here it goes, I hope it helps people. Any bug fixings or helpful modifications welcome :)

<SCRIPT LANGUAGE="JAVASCRIPT">
function RadioValidator()
{
    var ShowAlert = '';
    var AllFormElements = window.document.getElementById("FormID").elements;
    for (i = 0; i < AllFormElements.length; i++) 
    {
        if (AllFormElements[i].type == 'radio') 
        {
            var ThisRadio = AllFormElements[i].name;
            var ThisChecked = 'No';
            var AllRadioOptions = document.getElementsByName(ThisRadio);
            for (x = 0; x < AllRadioOptions.length; x++)
            {
                 if (AllRadioOptions[x].checked && ThisChecked == 'No')
                 {
                     ThisChecked = 'Yes';
                     break;
                 } 
            }   
            var AlreadySearched = ShowAlert.indexOf(ThisRadio);
            if (ThisChecked == 'No' && AlreadySearched == -1)
            {
            ShowAlert = ShowAlert + ThisRadio + ' radio button must be answered\n';
            }     
        }
    }
    if (ShowAlert != '')
    {
    alert(ShowAlert);
    return false;
    }
    else
    {
    return true;
    }
}
</SCRIPT>

HTML:

<label class="block"><input type="radio" name="calculation" value="add">+</label>
<label class="block"><input type="radio" name="calculation" value="sub">-</label>
<label class="block"><input type="radio" name="calculation" value="mul">*</label>
<label class="block"><input type="radio" name="calculation" value="div">/</label>

<p id="result"></p>

JAVAScript:

var options = document.getElementsByName("calculation");

for (var i = 0; i < options.length; i++) {
    if (options[i].checked) {
        // do whatever you want with the checked radio
        var calc = options[i].value;
        }
    }
    if(typeof calc == "undefined"){
        document.getElementById("result").innerHTML = " select the operation you want to perform";
        return false;
}

You can use this simple script. You may have multiple radio buttons with same names and different values.

var checked_gender = document.querySelector('input[name = "gender"]:checked');

if(checked_gender != null){  //Test if something was checked
alert(checked_gender.value); //Alert the value of the checked.
} else {
alert('Nothing checked'); //Alert, nothing was checked.
}

http://www.somacon.com/p143.php/

function getCheckedValue(radioObj) {
    if(!radioObj)
        return "";
    var radioLength = radioObj.length;
    if(radioLength == undefined)
        if(radioObj.checked)
            return radioObj.value;
        else
            return "";
    for(var i = 0; i < radioLength; i++) {
        if(radioObj[i].checked) {
            return radioObj[i].value;
        }
    }
    return "";
}

If you want vanilla JavaScript, don't want to clutter your markup by adding IDs on each radio button, and only care about modern browsers, the following functional approach is a little more tasteful to me than a for loop:

<form id="myForm">
<label>Who will be left?
  <label><input type="radio" name="output" value="knight" />Kurgan</label>
  <label><input type="radio" name="output" value="highlander" checked />Connor</label>
</label>
</form>

<script>
function getSelectedRadioValue (formElement, radioName) {
    return ([].slice.call(formElement[radioName]).filter(function (radio) {
        return radio.checked;
    }).pop() || {}).value;
}

var formEl = document.getElementById('myForm');
alert(
   getSelectedRadioValue(formEl, 'output') // 'highlander'
)
</script>

If neither is checked, it will return undefined (though you could change the line above to return something else, e.g., to get false returned, you could change the relevant line above to: }).pop() || {value:false}).value;).

There is also the forward-looking polyfill approach since the RadioNodeList interface should make it easy to just use a value property on the list of form child radio elements (found in the above code as formElement[radioName]), but that has its own problems: How to polyfill RadioNodeList?


if(document.querySelectorAll('input[type="radio"][name="name_of_radio"]:checked').length < 1)

Give radio buttons, same name but different IDs.

var verified1 = $('#SOME_ELEMENT1').val();
var verified2 = $('#SOME_ELEMENT2').val();
var final_answer = null;
if( $('#SOME_ELEMENT1').attr('checked') == 'checked' ){
  //condition
  final_answer = verified1;
}
else
{
  if($('#SOME_ELEMENT2').attr('checked') == 'checked'){
    //condition
    final_answer = verified2;
   }
   else
   {
     return false;
   }
}

HTML Code

<input type="radio" name="offline_payment_method" value="Cheque" >
<input type="radio" name="offline_payment_method" value="Wire Transfer" >

Javascript Code:

var off_payment_method = document.getElementsByName('offline_payment_method');
var ischecked_method = false;
for ( var i = 0; i < off_payment_method.length; i++) {
    if(off_payment_method[i].checked) {
        ischecked_method = true;
        break;
    }
}
if(!ischecked_method)   { //payment method button is not checked
    alert("Please choose Offline Payment Method");
}

this is a utility function I've created to solve this problem

    //define radio buttons, each with a common 'name' and distinct 'id'. 
    //       eg- <input type="radio" name="storageGroup" id="localStorage">
    //           <input type="radio" name="storageGroup" id="sessionStorage">
    //param-sGroupName: 'name' of the group. eg- "storageGroup"
    //return: 'id' of the checked radioButton. eg- "localStorage"
    //return: can be 'undefined'- be sure to check for that
    function checkedRadioBtn(sGroupName)
    {   
        var group = document.getElementsByName(sGroupName);

        for ( var i = 0; i < group.length; i++) {
            if (group.item(i).checked) {
                return group.item(i).id;
            } else if (group[0].type !== 'radio') {
                //if you find any in the group not a radio button return null
                return null;
            }
        }
    }

With jQuery, it'd be something like

if ($('input[name=gender]:checked').length > 0) {
    // do something here
}

Let me break that down into pieces to cover it more clearly. jQuery processes things from left to right.

input[name=gender]:checked
  1. input limits it to input tags.
  2. [name=gender] limits it to tags with the name gender within the previous group.
  3. :checked limits it to checkboxes/radio buttons that are selected within the previous group.

If you want to avoid this altogether, mark one of the radio buttons as checked (checked="checked") in the HTML code, which would guarantee that one radio button is always selected.


Note this behavior wit jQuery when getting radio input values:

$('input[name="myRadio"]').change(function(e) { // Select the radio input group

    // This returns the value of the checked radio button
    // which triggered the event.
    console.log( $(this).val() ); 

    // but this will return the first radio button's value,
    // regardless of checked state of the radio group.
    console.log( $('input[name="myRadio"]').val() ); 

});

So $('input[name="myRadio"]').val() does not return the checked value of the radio input, as you might expect -- it returns the first radio button's value.


There is very sophisticated way you can validate whether any of the radio buttons are checked with ECMA6 and method .some().

Html:

<input type="radio" name="status" id="marriedId" value="Married" />
<input type="radio" name="status" id="divorcedId" value="Divorced" />

And javascript:

let htmlNodes = document.getElementsByName('status');

let radioButtonsArray = Array.from(htmlNodes);

let isAnyRadioButtonChecked = radioButtonsArray.some(element => element.checked);

isAnyRadioButtonChecked will be true if some of the radio buttons are checked and false if neither of them are checked.


An example:

if (!checkRadioArray(document.ExamEntry.level)) { 
    msg+="What is your level of entry? \n"; 
    document.getElementById('entry').style.color="red"; 
    result = false; 
} 

if(msg==""){ 
    return result;  
} 
else{ 
    alert(msg) 
    return result;
} 

function Radio() { 
    var level = radio.value; 
    alert("Your level is: " + level + " \nIf this is not the level your taking then please choose another.") 
} 

function checkRadioArray(radioButtons) { 
    for(var r=0;r < radioButtons.length; r++) { 
        if (radioButtons[r].checked) { 
            return true; 
        } 
    } 
    return false; 
} 

With JQuery, another way to check the current status of the radio buttons is to get the attribute 'checked'.

For Example:

<input type="radio" name="gender_male" value="Male" />
<input type="radio" name="gender_female" value="Female" />

In this case you can check the buttons using:

if ($("#gender_male").attr("checked") == true) {
...
}

A vanilla JavaScript way

var radios = document.getElementsByTagName('input');
var value;
for (var i = 0; i < radios.length; i++) {
    if (radios[i].type === 'radio' && radios[i].checked) {
        // get value, set checked flag or do whatever you need to
        value = radios[i].value;       
    }
}

I just want to ensure something gets selected (using jQuery):

// html
<input name="gender" type="radio" value="M" /> Male <input name="gender" type="radio" value="F" /> Female

// gender (required)
var gender_check = $('input:radio[name=gender]:checked').val();
if ( !gender_check ) {
    alert("Please select your gender.");
    return false;
}