Question

I am working on a website with several forms of radio buttons, one of which is like this:

<form id = "configuration">
    <ul>
        <li><input type="radio" name="configuration" id="0" value="0"/> GT Manual</li>
        <li><input type="radio" name="configuration" id="1" value="1"/> GT Automatic</li>
    </ul>
</form>

IS THERE a way (javascript) that I can access the value of the radio buttons directly, e.g.

var value = document.getElementById("configuration").configuration.value;

(here the first "configuration" is the form id while the second 'configuration' is the name, rather than looping through each element in the form to check which button is selected?

Thank you!

No correct solution

OTHER TIPS

Get it like this...

var radios = document.getElementsByName('configuration');
 for (i = 0; i < radios.length; i++) {
    if (radios[i].type == 'radio' && radios[i].checked) {
        alert(radios[i].value);
    }
}

No. You have to loop over the radio group to find out which one is selected. .configuration is a standard NodeList, not a 'subclass' with extra features for handling radio groups.

Since the Radio buttons are part of a group they have the same name are are identified by a distinct ID. The answer provided by KyleK is perfectly valid. However here is another way to do it http://jsfiddle.net/9W76C/

if (document.getElementById('0').checked) {
   alert("GT Manual");
}

I would also suggest you use jquery...

If you're using jQuery, you can do $('#configuration input:checkbox').val(); to know which one is selected

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top