Clueless Gorilla
Clueless Gorilla

Reputation: 1229

access radio button value through form id

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!

Upvotes: 4

Views: 767

Answers (4)

user2479365
user2479365

Reputation: 633

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

Upvotes: -1

Kylie
Kylie

Reputation: 11749

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);
    }
}

Upvotes: 2

AnaMaria
AnaMaria

Reputation: 3621

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

Upvotes: -1

Quentin
Quentin

Reputation: 943216

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.

Upvotes: 1

Related Questions