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



<html>
    <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>
RUN
Male Female Other gender

Comments

Post a Comment

Popular posts from this blog

python pattern programming

Decision making statement in python

javaScript Calculator.