Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the value of a radio button with pure javascript?

<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?

like image 593
Davis Dimitriov Avatar asked Nov 02 '11 19:11

Davis Dimitriov


3 Answers

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.

like image 114
James Johnson Avatar answered Nov 04 '22 02:11

James Johnson


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

var selectedColor = document.all["colors"];
like image 27
Glenn Ferrie Avatar answered Nov 04 '22 03:11

Glenn Ferrie


plain javasript:

document.querySelector('input[name=colors]:checked').value;
like image 29
Bernhard Wagner Avatar answered Nov 04 '22 02:11

Bernhard Wagner