How can I check whether a radio button is selected with JavaScript?
Asked Answered
M

30

335

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?

Melitamelitopol answered 14/9, 2009 at 20:35 Comment(1)
this link may help you #6655101Retribution
H
399

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.

Hedelman answered 14/9, 2009 at 20:37 Comment(8)
but what i want to check if a radio button is selected regardless of what is selected.Melitamelitopol
I don't really follow what you're saying? Are interested in whether or not ANY radio button is selected?Hedelman
yes. because the form cannot be submitted if not all the fields are filled-in including the radio buttons.Melitamelitopol
if (document.getElementById('gender_Male').checked || document.getElementById('gender_Female').checked) alert('some of my radioboxes is checked');Gurglet
I've modified my Prototype example to take advantage of the CSS selector lesson I just learned from R. Bemrose.Hedelman
how would this check if user has selected input id on the fly? example if we have two ids and user selects one or other over and over. i ask because the code you have checks on page load fine, but if you deselect and then select the certain ID again the script does not function.Knockwurst
@HollerTrain There isn't anything in this answer about page load. If you wanted to check on the fly, you'd have to add a click handler to the radio buttons.Hedelman
This is more simplify question and we should go for native from nowMaudemaudie
T
141

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.

Toein answered 14/9, 2009 at 20:49 Comment(4)
-1 for proposing a library when unasked for. This way we could answer everything with "include library x, use x.doWhatYouNeed()". No flame intended, I genuinely think this question should be answered with pure javascript (and then eventually point out how easier it is with a library)Parable
@RiccardoGalli: A lot of people already use jQuery, hence why the answer starts with "With jQuery, it'd be something like" in case they were already using it.Toein
Anyone know if it is possible to chain selectors like this? input[name=gender][type=radio] or input[name=gender,type=radio] just for extra validation?Algerian
@EW-CodeMonkey The first way you mentioned should work.Toein
S
90

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;       
    }
}
Scyphozoan answered 14/9, 2009 at 20:53 Comment(7)
Well i got almost the same problem right now and your code was very helpfullSmokechaser
This would get you the value of the last checked radio button. If you have multiple radio groups then this probably won't get you the correct value.Baptize
@Baptize This works fine for the OP's question where he states that there are only two radio buttons in a form on the page. The solution would be different for a different problem scenario such as more than two radio buttons, multiple radio groups, etc :)Scyphozoan
@RussCam Yes this works for a tiny page with only 2 radio buttons, but I added my comment to make the answer complete. The best way to get the radio button elements would be by name.Baptize
A better way would be to select radio elements by a particular class, and then group different groups of radio elements into different classes. Otherwise, this solution as it is would only work for one group of radio elements with no other input form elements.Saxen
@Tobsta feel free to edit and update the answer; it was written in 2009, when not every browser supported document.getElementsByClassName() or the Selectors API :)Scyphozoan
@RussCam True, I guess I should.Saxen
C
28

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.
}
Chorion answered 5/11, 2017 at 15:9 Comment(3)
+1. This is the shortest Vanilla JS solution to get the checked radio element, what we need in some cases. I think you have the best answer because of this. And for only getting value we could use document.forms[0].elements['nameOfRadioList'].valueWigging
I second what @Wigging said, this is the best answer so far. Concise, correct, up-to-date.Yonder
If you've been staring at the screen for a long time you might miss it.....this solution uses querySelector not querySelectorAll. I kept getting undefined....... :-)Indict
H
19

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.

Hobbism answered 25/9, 2015 at 11:28 Comment(3)
may be it should be var radios = document.querySelectorAll('input[type="radio"]:checked');Across
@ShafiqurRahman you're absolutely right, I'll update my answer, I don't think you need the quotes around radio.Hobbism
+1 for Vanilla JavaScript. I would always use the quotes around attribute values, since for some other attribute values, (such as a[href^="http://"]) they would be required, and consistency is more maintainable. Besides, this lets the attribute declaration match the corresponding HTML.Overcrop
G
13

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");
}
Glowing answered 12/4, 2012 at 7:23 Comment(1)
Warning: this code returns the popup warning as soon as the page loads.Extension
G
9

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>
Glorify answered 29/11, 2012 at 11:19 Comment(0)
Y
9

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

I share for whom concern.

var checked = [...document.getElementsByName("gender")].some(c=>c.checked);
console.log(checked);
<input type="radio" name="gender" checked value="Male" /> Male
<input type="radio" name="gender"  value="Female" / > Female
Year answered 8/6, 2020 at 2:2 Comment(1)
I love your answer @Hien Nguyen, it was something I was trying to come up with (with the idea of using "any()", but I found out that JavaScript only uses "some()". Please can someone tell me though what the "triple-dot" means? It doesn't work without it.Celebrate
A
7

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)
Antisepticize answered 3/10, 2014 at 12:12 Comment(1)
// Check if something in radio group is choosen if ($$('input[name=radiosname]:checked').length > 0) was exactly what i neededCourtroom
M
6

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.

Mozart answered 13/11, 2013 at 22:56 Comment(0)
I
5

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.

Insinuate answered 8/5, 2019 at 8:5 Comment(0)
A
4
if(document.querySelectorAll('input[type="radio"][name="name_of_radio"]:checked').length < 1)
Across answered 1/10, 2016 at 10:49 Comment(0)
H
4

Return all checked element in the radio button

  Array.from(document.getElementsByClassName("className")).filter(x=>x['checked']);
Halvorsen answered 22/6, 2019 at 5:40 Comment(0)
A
3

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;
            }
        }
    }
Actor answered 7/10, 2012 at 6:34 Comment(1)
Like this because its (re)usability and simplicity. Also, returned value can be handled by a nice switch statement.Otha
M
3

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 });
Middleweight answered 1/9, 2014 at 14:49 Comment(0)
G
2

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>
Ganges answered 30/7, 2011 at 7:10 Comment(2)
getElementsByName() returns an HTMLCollection, which wouldn't have a checked property, so I don't believe the JavaScript snippet you posted would work as intended. You'd have to loop over the elements in the HTMLCollection and see if any of them are checked, as others have suggested.Salerno
thanks. you are correct.:) updated my reply, so as no more peoples get wrong info .Ganges
F
2

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) {
...
}
Flamethrower answered 24/1, 2013 at 11:41 Comment(1)
In my case, value of $("#gender_male").attr("checked") is a string "checked" and not a boolean.Rakel
F
2

Try

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

function check() {
  let v= ([...myForm.sex].filter(r=>r.checked)[0] || {}).value ;
  console.log(v);
}
<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>
Fauteuil answered 3/8, 2020 at 21:26 Comment(1)
This is the brilliant one-liner I've been searching for - returns the value of the checked radio button, not just whether one of the radio buttons is checked.Nubile
P
2

So basically, what this code does is to loop through a nodeList that contains all the input elements. In case one of these input elements is of type radio and is checked then do something and break the loop.

If the loop doesn't detect an input element been selected, the boolean variable selected will stay false, and applying a conditional statement we can execute something for this case.

let inputs = document.querySelectorAll('input')
let btn = document.getElementById('btn')
let selected = false

function check(){
  for(const input of inputs){
    if(input.type === 'radio' && input.checked){
      console.log(`selected: ${input.value}`) 
      selected = true
      break
    }
  }
  if(!selected) console.log(`no selection`)
}

btn.addEventListener('click', check)
<input type="radio" name="option" value="one">
<label>one</label>
<br>
<input type="radio" name="option" value="two">
<label>two</label>
<br>
<br>
<button id="btn">check selection</button>
Pelt answered 13/1, 2022 at 15:11 Comment(0)
B
1

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 "";
}
Bow answered 4/8, 2012 at 17:51 Comment(0)
U
1

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;
}
Upbraiding answered 20/5, 2013 at 18:39 Comment(0)
L
1

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

$("form").submit(function(e) {
  e.preventDefault();
  $this = $(this);

  var value = $this.find('input:radio[name=COLOR]:checked').val();
  alert(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input name="COLOR" id="Rojo" type="radio" value="red">
  <input name="COLOR" id="Azul" type="radio" value="blue">
  <input name="COLOR" id="Amarillo" type="radio" value="yellow">
  <br>
  <input type="submit" value="Submit">
</form>
Levi answered 8/4, 2015 at 15:9 Comment(0)
M
1

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;
}
Mozarab answered 7/3, 2017 at 6:34 Comment(0)
U
0

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.

Unforgettable answered 26/1, 2013 at 15:31 Comment(1)
You could simply do: if (!document.getElementById('radio1').checked && !document.getElementById('radio2').checked) { alert(); }.Byington
M
0

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; 
} 
Manno answered 21/3, 2013 at 7:41 Comment(0)
M
0

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/

Men answered 16/4, 2013 at 12:6 Comment(0)
A
0

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?

Ancipital answered 7/6, 2013 at 0:4 Comment(0)
R
0

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;
}
Reinhardt answered 15/1, 2016 at 18:11 Comment(0)
R
0

My 2 cents:

function valid(inputs) {
  if (inputs.RadioOption.value === "") {
      alert("Please, select radio option");
  }
}
<form onsubmit="return valid(this);">
    <div>
        <input type="radio" name="RadioOption" value="1"> Radio option 1
        <input type="radio" name="RadioOption" value="2"> Radio option 1
        <input type="radio" name="RadioOption" value="3"> Radio option 1
    </div>
    <div>
        <input type="submit" value="Check Radio Group">
    </div>
</form>
Responsum answered 10/11, 2023 at 7:33 Comment(0)
B
-2

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;
   }
}
Brietta answered 17/5, 2013 at 15:19 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.