Javascript Form How to - Get selected value from RadioButton group








Question

We would like to know how to get selected value from RadioButton group.

Answer


<html> 
<head> 
<script type="text/javascript"> 
function processData(form) { <!--from  ww  w  .  ja  va 2  s  .  c o m-->
    for (var i = 0; i < form.Beatles.length; i++) { 
        if (form.Beatles[i].checked) { 
            break; 
        } 
    } 
    var chosenBeatle = form.Beatles[i].value; 
    var chosenSong = form.song.value; 
    console.log(chosenSong + " " + chosenBeatle ); 
} 
function checkSong(songTitle) { 
    var enteredSong = songTitle.value; 
    console.log(enteredSong); 
} 
</script> 
</head> 
<body> 
<form name=""> 
Choose your favorite Beatle: 
<input type="radio" name="Beatles" id="Beatles1" value="John Lennon" checked="true" />John 
<input type="radio" name="Beatles" id="Beatles2" value="Paul McCartney" />Paul 
<input type="radio" name="Beatles" id="Beatles3" value="George Harrison" />George 
<input type="radio" name="Beatles" id="Beatles4" value="Ringo Starr" />Ringo 
<p>Enter the name of your favorite Beatles song:<br /> 
<input type="text" name="song" id="song" value="value" onchange="checkSong(this)" /></p> 
<p><input type="button" name="process" id="process" value="Process" onclick="processData(this.form)" /></p> 
</form> 
</body> 
</html>

The code above is rendered as follows: