5

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.

1
  • Have you checked the code repository at javascript.internet.com? You've got to write a loop and check each of the buttons for the selected value. Commented Nov 22, 2011 at 20:37

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your advice on my previous post and the response here, I shall try it and see what I can make
@JosephRobins, please see updated post. There was a bug in my previous answer.
Oh you beauty! I am so happy now :):):) Thanks so much for all your help!
1

you can get a more simple and elegant solution:

<input type=radio name=my_radio value=value_1>

var my_form = document.querySelector('#my_form');
var my_radio = my_form.elements.my_radio;

alert(my_radio.value)  // this is the radionodelist.value you can check it on mdn

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.