339

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?

0

29 Answers 29

400

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.

Sign up to request clarification or add additional context in comments.

8 Comments

but what i want to check if a radio button is selected regardless of what is selected.
I don't really follow what you're saying? Are interested in whether or not ANY radio button is selected?
yes. because the form cannot be submitted if not all the fields are filled-in including the radio buttons.
if (document.getElementById('gender_Male').checked || document.getElementById('gender_Female').checked) alert('some of my radioboxes is checked');
I've modified my Prototype example to take advantage of the CSS selector lesson I just learned from R. Bemrose.
|
144

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.

Comments

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

7 Comments

Well i got almost the same problem right now and your code was very helpfull
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 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 :)
@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.
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.
|
31

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

3 Comments

+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
I second what @Bharata said, this is the best answer so far. Concise, correct, up-to-date.
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....... :-)
20

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.

3 Comments

may be it should be var radios = document.querySelectorAll('input[type="radio"]:checked');
@ShafiqurRahman you're absolutely right, I'll update my answer, I don't think you need the quotes around radio.
+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.
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"); } 

1 Comment

Warning: this code returns the popup warning as soon as the page loads.
10

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

1 Comment

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

Comments

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) 

1 Comment

// Check if something in radio group is choosen if ($$('input[name=radiosname]:checked').length > 0) was exactly what i needed
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.

Comments

6

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.

Comments

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

Comments

4

Return all checked element in the radio button

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

Comments

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

1 Comment

Like this because its (re)usability and simplicity. Also, returned value can be handled by a nice switch statement.
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 }); 

Comments

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

1 Comment

In my case, value of $("#gender_male").attr("checked") is a string "checked" and not a boolean.
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> 

Comments

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>

1 Comment

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

Comments

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

Comments

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

Comments

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>

Comments

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

Comments

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.

1 Comment

You could simply do: if (!document.getElementById('radio1').checked && !document.getElementById('radio2').checked) { alert(); }.
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; } 

Comments

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/

Comments

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?

Comments

0

This might be helpful as well. It will return the input element that is currently selected.

const inputs = document.querySelectorAll('input.my-class'); const selectedInput = Array.from(inputs).find(input => input.checked); console.log(selectedInput.value)
<input type="radio" class="my-class" value="one-time" > <input type="radio" class="my-class" value="subscription" checked="checked">

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.