How to get value of selected radio button using JavaScript ?
How to get value of selected radio button using JavaScript ?
To get the vale of selected radio button,create a function that function gets all the radio button using with the Name attribute and finds the radio button selected using checked property.The checked property return true or false.If radio button is checked it returns true otherwise it returns false.
If we use multiple radio button than each button has its own index value therefore we access selected radio button using this index value.
After get value we display result in a box using innerHTML.
FOR EXAMPLE THE FOLLOWING PROGRAM DISPLAY THE SELECTED RADIO BUTTON VALUE
<body>
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="Female">Female
<input type="radio" name="gender" value="Other gender">Other gender
<button id="check">check selected</button>
<div id="box"></div>
</body>
<script>
var genderSelected=document.getElementsByName("gender");
var check=document.getElementById("check");
check.onclick=function(){
for(i=0;i<genderSelected.length;i++){
if(genderSelected[i].checked){
document.getElementById("box").innerHTML="Selected Gender : "+genderSelected[i].value;}
}
}
</script>
</html>
Male Female Other gender
Mast anku
ReplyDelete