Javascript Form How to - Loop through each Radio Button and get the selected ones








Question

We would like to know how to loop through each Radio Button and get the selected ones.

Answer


<html>
<head>
<script language = "JavaScript">
     function getRadioValue(radioObject) {
          var value = null
          for (var i=0; i<radioObject.length; i++) {
               if (radioObject[i].checked) {
                    value = radioObject[i].value;
                    break ;<!--from w w  w  . j av a 2 s.  c om-->
               }
          }
          return value
     }
</script>
</head>
<body>
    <form name="form1">
    <p><input type=radio name="songs" value="A">A</p>
    <p><input type=radio name="songs" value="B">B</p>
    <p><input type=radio name="songs" value="C">C</p>
    <input type=button value="Show Selected" onClick="console.log(getRadioValue(this.form.songs))">
    </form>
</body>
</html>

The code above is rendered as follows: