5

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

Daniel Silveira
  • 41,125
  • 36
  • 100
  • 121
  • What do you want to use the option for ?-) Torbjørns answer returns the value, which in most situations would be sufficient, but sometimes it could be possible to do other things ... – roenving Oct 02 '08 at 13:55
  • I'm guessing he meant the value.... – Torbjørn Oct 02 '08 at 13:59

4 Answers4

10
<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
  • 7,860
  • 8
  • 36
  • 48
  • 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 Oct 02 '08 at 14:47
  • You're right... but I think Daniel got the idea. Anyway, I changed "document.all" to "document.getElementsByName" – leoinfo Oct 02 '08 at 15:03
2

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

Torbjørn
  • 6,423
  • 5
  • 29
  • 42
2

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
  • 38,646
  • 4
  • 37
  • 49
0

generic functions (loosely based on yours )

function getRadioGroupSelectedElement(radioGroupName) {

    var radioGroup = document.getElementsByName(radioGroupName);
    var radioElement = radioGroup.length - 1;
    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;
}
kraag22
  • 3,340
  • 3
  • 29
  • 37