checking if at least one radio button has been selected - JavaScript

Something like this should do the trick

if ($("input[type=radio]:checked").length > 0) {
    // Do your stuff here
}

UPDATE Did not see that it's not supposed to have jQuery, so here's an alternative function to check that in pure JS

 function check(){
     var radios = document.getElementsByName("choice");

     for (var i = 0, len = radios.length; i < len; i++) {
          if (radios[i].checked) {
              return true;
          }
     }

     return false;
 }

Looping over the <input> tags, check the type and if it is checked.

function isOneChecked() {
  // All <input> tags...
  var chx = document.getElementsByTagName('input');
  for (var i=0; i<chx.length; i++) {
    // If you have more than one radio group, also check the name attribute
    // for the one you want as in && chx[i].name == 'choose'
    // Return true from the function on first match of a checked item
    if (chx[i].type == 'radio' && chx[i].checked) {
      return true;
    } 
  }
  // End of the loop, return false
  return false;
}

Here it is in action on jsfiddle


This is possible to do without javascript if your targeted browsers support the HTML5 required attribute.

<input type="radio" name="choose" value="psychology" required>
<input type="radio" name="choose" value="geography" required>
<input type="radio" name="choose" value="gastronomy" required>

Note that in chrome you only need to put required on one of the inputs. I am not sure what other browsers do.

I usually do this in addition to a javascript validation (like the selected answers) so that html 4 browsers are supported as well.

Tags:

Javascript