331

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?

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
noob
  • 4,699
  • 10
  • 33
  • 32

29 Answers29

396

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.

Pragnesh Rupapara
  • 782
  • 1
  • 12
  • 30
Mark Biek
  • 146,731
  • 54
  • 156
  • 201
  • 2
    but what i want to check if a radio button is selected regardless of what is selected. – noob Sep 14 '09 at 20:39
  • 1
    I don't really follow what you're saying? Are interested in whether or not ANY radio button is selected? – Mark Biek Sep 14 '09 at 20:41
  • yes. because the form cannot be submitted if not all the fields are filled-in including the radio buttons. – noob Sep 14 '09 at 20:42
  • if (document.getElementById('gender_Male').checked || document.getElementById('gender_Female').checked) alert('some of my radioboxes is checked'); – Havenard Sep 14 '09 at 20:44
  • I've modified my Prototype example to take advantage of the CSS selector lesson I just learned from R. Bemrose. – Mark Biek Sep 14 '09 at 20:54
  • 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. – Zach Smith Jan 19 '17 at 07:29
  • @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. – Mark Biek Jan 19 '17 at 11:57
  • This is more simplify question and we should go for native from now – Faris Rayhan Jan 20 '18 at 09:33
139

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.

Powerlord
  • 87,612
  • 17
  • 125
  • 175
  • 34
    -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) – Riccardo Galli Sep 21 '12 at 14:16
  • 36
    @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. – Powerlord Sep 21 '12 at 17:30
  • 1
    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? – Ty_ Nov 17 '15 at 15:26
  • @EW-CodeMonkey The first way you mentioned [should work](https://api.jquery.com/multiple-attribute-selector/). – Powerlord Nov 17 '15 at 16:56
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;       
    }
}
Russ Cam
  • 124,184
  • 33
  • 204
  • 266
  • 2
    Well i got almost the same problem right now and your code was very helpfull – MoreThanChaos Nov 26 '09 at 07:00
  • 2
    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. – styfle Oct 05 '12 at 16:44
  • @styfle 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 :) – Russ Cam Oct 06 '12 at 06:49
  • 2
    @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`. – styfle Oct 09 '12 at 20:35
  • 1
    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. – Oliver Aug 08 '16 at 11:15
  • @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 :) – Russ Cam Aug 08 '16 at 11:39
  • @RussCam True, I guess I should. – Oliver Aug 09 '16 at 11:44
26

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.
}
Neri
  • 738
  • 1
  • 8
  • 19
  • 2
    +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'].value` – Bharata Jun 22 '20 at 14:20
  • I second what @Bharata said, this is the best answer so far. Concise, correct, up-to-date. – Aquarelle Sep 28 '21 at 11:07
  • 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....... :-) – Adrian Mar 14 '22 at 22:13
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.

Community
  • 1
  • 1
Matt McCabe
  • 2,986
  • 2
  • 22
  • 29
  • may be it should be var radios = document.querySelectorAll('input[type="radio"]:checked'); – Md. Shafiqur Rahman Jul 16 '16 at 11:17
  • @ShafiqurRahman you're absolutely right, I'll update my answer, I don't think you need the quotes around radio. – Matt McCabe Jul 18 '16 at 19:29
  • 4
    +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. – Manngo Jul 22 '16 at 04:07
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");
}
Community
  • 1
  • 1
Amit sharma
  • 139
  • 1
  • 4
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>
wandarkaf
  • 1,839
  • 20
  • 30
Trelamenos
  • 91
  • 1
  • 1
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
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
  • 4
    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. – Jonno May 05 '21 at 17:06
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)
marbel82
  • 925
  • 1
  • 18
  • 39
  • 1
    // Check if something in radio group is choosen if ($$('input[name=radiosname]:checked').length > 0) was exactly what i needed – Steve Johnson Mar 07 '15 at 22:42
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.

Bradley Flood
  • 10,233
  • 3
  • 46
  • 43
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.

OlegI
  • 5,472
  • 4
  • 23
  • 31
4
if(document.querySelectorAll('input[type="radio"][name="name_of_radio"]:checked').length < 1)
Md. Shafiqur Rahman
  • 2,878
  • 27
  • 24
4

Return all checked element in the radio button

  Array.from(document.getElementsByClassName("className")).filter(x=>x['checked']);
Ashish
  • 2,026
  • 17
  • 19
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;
            }
        }
    }
Gene Myers
  • 1,230
  • 1
  • 14
  • 31
  • 1
    Like this because its (re)usability and simplicity. Also, returned value can be handled by a nice switch statement. – JGurtz Apr 29 '14 at 23:29
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 });
Uxío
  • 1,333
  • 11
  • 12
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) {
...
}
Claudio Query
  • 323
  • 1
  • 4
  • 13
  • 1
    In my case, value of `$("#gender_male").attr("checked")` is a string `"checked"` and not a boolean. – Koks_rs Feb 05 '16 at 10:49
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>
Rubyist
  • 6,486
  • 10
  • 51
  • 86
Parag
  • 4,754
  • 9
  • 33
  • 50
  • 1
    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. – Rudi Jul 10 '12 at 01:46
  • thanks. you are correct.:) updated my reply, so as no more peoples get wrong info . – Parag Jul 11 '12 at 05:55
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>
Gass
  • 7,536
  • 3
  • 37
  • 41
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 "";
}
keithics
  • 8,576
  • 2
  • 48
  • 35
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>
Jon Doe
  • 2,172
  • 1
  • 18
  • 35
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;
}
vijay rami
  • 535
  • 4
  • 19
1

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>
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
  • 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. – cssyphus Jun 27 '23 at 14:35
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.

insertusernamehere
  • 23,204
  • 9
  • 87
  • 126
Steve
  • 1
  • 1
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; 
} 
Artem Shmatkov
  • 1,434
  • 5
  • 22
  • 41
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/

gaby de wilde
  • 1,313
  • 12
  • 6
0

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;
}
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?

Community
  • 1
  • 1
Brett Zamir
  • 14,034
  • 6
  • 54
  • 77
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;
}
jHilscher
  • 1,810
  • 2
  • 25
  • 29
-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;
   }
}
Rubyist
  • 6,486
  • 10
  • 51
  • 86
CG_DEV
  • 788
  • 7
  • 7