Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

Supposed I had the following HTML form:

<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  <title>Choose</title>
</head>

<body>
  <form method="post" enctype="application/x-www-form-urlencoded">
    <h1>Choose</h1>

    <p><input type="radio" name="choose" value="psychology"><font size="5" color="#0033CC">Instant Psychology</font><br>
    <br>
    <input type="radio" name="choose" value="geography"><font size="5" color="#CC0000">Instant Geography</font><br>
    <br>
    <input type="radio" name="choose" value="gastronomy"><font size="5" color="#660033">Instant Gastronomy</font><br>
    <br>
    <input type="submit" name="Submit" value="Go"></p>
  </form>


</body><link rel="stylesheet" type="text/css" href="data:text/css,"></html>

How can I write a JavaScript function to make sure at least one radio input has been selected?

like image 525
cybertextron Avatar asked Oct 25 '12 01:10

cybertextron


2 Answers

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;
 }
like image 187
pedrochaves Avatar answered Nov 04 '22 18:11

pedrochaves


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.

like image 14
Rick Smith Avatar answered Nov 04 '22 17:11

Rick Smith