Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the value from a radio button using javascript

I have a HTML form with radio inputs and want to use javascript to analyse the results. I am getting stuck at retrieving the form information in my JavaScript function:

function getResults(formInput){
    alert (formInput.question1);
}

Where question1 is the "name" of my radio button group.

This returns "object Nodelist" and I haven't a clue what's wrong, I would expect it to return "1", which is the value of my radio button when selected.

I don't want to work out which radio button is selected and which isn't, I need to know the value associated with the selected radio button.

like image 402
Joseph Robins Avatar asked Nov 22 '11 20:11

Joseph Robins


1 Answers

The object Nodelist that you're referring to is being returned because you have a group of elements that share the same name. If you want to see the value of the radio button that's checked, you need to loop through the collection:

function getResults() {
    var radios = document.getElementsByName("question1");

    for (var i = 0; i < radios.length; i++) {       
        if (radios[i].checked) {
            alert(radios[i].value);
            break;
        }
    }
}

Here's a working jsFiddle.

like image 167
James Hill Avatar answered Sep 28 '22 09:09

James Hill