tags:

views:

703

answers:

4

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

+3  A: 

http://www.somacon.com/p143.php

Torbjørn
+2  A: 
<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>
leoinfo
But using document.all to get elements is a bad practice as it only works in a few browsers, use the standard document.getElementsByName instead !-)
roenving
You're right... but I think Daniel got the idea.Anyway, I changed "document.all" to "document.getElementsByName"
leoinfo
+2  A: 

If you need the actual element and not just the selected value, try this:

function findSelected(){
  for (i=0;i<document.formname.radioname.length;i++){
    if (document.formname.radioname[i].checked){
      return document.formname.radioname[i];
    }
  }
}
Wayne
A: 

generic functions (loosely based on yours )

function getRadioGroupSelectedElement(radioGroupName) {

var radioGroup = document.getElementsByName(radioGroupName);
var radioElement = radioGroup.length;
for(radioElement; radioElement >= 0; radioElement--) {
    if(radioGroup[radioElement].checked){
        return radioGroup[radioElement];
    }
}
return false;

}

function getRadioGroupSelectedValue(radioGroupName) {

var selectedRadio = getRadioGroupSelectedElement(radioGroupName);
if (selectedRadio !== false) {
    return selectedRadio.value;
}
return false;

}

Markus Albe