Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 924
noob Avatar asked Sep 14 '09 20:09

noob


People also ask

How check multiple radio button is checked or not in JavaScript?

What you should do is set up two variables, both of them serving as boolean flags. Then loop through each set of radio buttons in order to determine if a button has been selected. If so, set the corresponding flag to true, otherwise false. Then at the end, test to see if both flags have been set to true.


1 Answers

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.

like image 129
Mark Biek Avatar answered Oct 13 '22 06:10

Mark Biek