Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the checked option in a group of radio inputs with JavaScript?

Tags:

javascript

How to get the checked option in a group of radio inputs with JavaScript?

like image 656
Daniel Silveira Avatar asked Oct 02 '08 13:10

Daniel Silveira


People also ask

How can I check if a radio button group is selected?

To find the selected radio button, you follow these steps: Select all radio buttons by using a DOM method such as querySelectorAll() method. Get the checked property of the radio button. If the checked property is true , the radio button is checked; otherwise, it is unchecked.


1 Answers

<html>
  <head>
    <script type="text/javascript">
      function testR(){
        var x = document.getElementsByName('r')
        for(var k=0;k<x.length;k++)
          if(x[k].checked){
            alert('Option selected: ' + x[k].value)
          }

      }
    </script>
  </head>
  <body>
    <form>
      <input type="radio" id="r1" name="r" value="1">Yes</input>
      <input type="radio" id="r2" name="r" value="2">No</input>
      <input type="radio" id="r3" name="r" value="3">Don't Know</input>
      <br/>
      <input type="button" name="check" value="Test" onclick="testR()"/>
    </form>
  </body>
</html>
like image 156
leoinfo Avatar answered Oct 13 '22 00:10

leoinfo