9
<input checked=checked type="radio" name="colors" value="red" />Red
<input type="radio" name="colors" value="green" />Green
<input type="radio" name="colors" value="blue" />Blue

Given the above, I set the red button to be selected by default (so I give it the checked=checked attribute. With this, if I ever call .checked on that input element, it will always return true, even if another option is selected.

In plain javascript (no jQuery), how can you get the actual selected option?

Davis Dimitriov
  • 4,159
  • 3
  • 31
  • 45
  • possible duplicate of [How to I get the value of a radio button with javascript](http://stackoverflow.com/questions/3778206/how-to-i-get-the-value-of-a-radio-button-with-javascript) – Michael Berkowski Nov 02 '11 at 19:45

5 Answers5

10

Try this:

var options = document.getElementsByName("colors");
if (options) {
    for (var i = 0; i < options.length; i++) {
        if (options[i].checked){
             alert(options[i].value);
        }
    }
}

Would be so much easier with jQuery though... just saying.

James Johnson
  • 45,496
  • 8
  • 73
  • 110
  • this is basically what I am doing right now, but like I said, the .checked always returns true for the red input element, since it was explicitly set with checked=checked when it was created, even though another option was selected since then – Davis Dimitriov Nov 02 '11 at 19:54
  • Why are you defaulting the options to checked? – James Johnson Nov 02 '11 at 19:56
  • in this case, red needs to be checked by default. Is there another way around this maybe? – Davis Dimitriov Nov 02 '11 at 19:57
2

plain javasript:

document.querySelector('input[name=colors]:checked').value;
Bernhard Wagner
  • 1,681
  • 12
  • 15
1

I believe you will find it in the document.all collection:

var selectedColor = document.all["colors"];
Glenn Ferrie
  • 10,290
  • 3
  • 42
  • 73
0

you can try like this .....

This is example

<form name="frmRadio" method="post">
<input name="choice" value="1" type="radio" />1 
<input name="choice" value="2" type="radio" />2 
<input name="choice" value="3" type="radio" />3 
<input name="choice" value="4" type="radio" />4
</form>

function to get the selected value

<script language="JavaScript">

    function getRadioValue() {
        for (index=0; index < document.frmRadio.choice.length; index++) {
            if (document.frmRadio.choice[index].checked) {
                var radioValue = document.frmRadio.choice[index].value;
                break;
            }
        }
    }

</script>
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Glory Raj
  • 17,397
  • 27
  • 100
  • 203
-1

Well, they all have the same name. So naturally at least one of them has to be selected. Give them different ID's and try again.

Techboy6601
  • 110
  • 1
  • 11