Javascript Form How to - Get selected value for RadioButton via Radio Button Group








Question

We would like to know how to get selected value for RadioButton via Radio Button Group.

Answer


 <!--from w ww.  ja va 2 s.  c om-->
<html>
<head>
<script language="javascript" type="text/javascript">
function evalGroup(){
     var group = document.radioForm.myRadio;
     console.log(group.length);
     for (var i=0; i<group.length; i++) {
       if (group[i].checked)
          break;
     }
     if (i==group.length)
        return console.log("No radio button is checked");
     console.log("Radio Button " + (i+1) + " is checked.");
}
</script>
</head>
<body>

<form name="radioForm">
  Radio Button 1: <input type="radio" name="myRadio" /><br />
  Radio Button 2: <input type="radio" name="myRadio" /><br />
  Radio Button 3: <input type="radio" name="myRadio" /><br />
  Radio Button 4: <input type="radio" name="myRadio" /><br /><br />
  <input type="button" value="Eval Group" onclick="evalGroup()" />
</form>

</body>
</html>

The code above is rendered as follows: