Quirah
Quirah

Reputation: 5

Getting value of radio button with Javascript in same HTML page

I'm new on javascript coding.

I'm kinda creating a survey page by myself. I will ask question as a 'True or False' and will get True as a 1 point, false as a 0 point. there will be multiple questions.

I tried to do it by getElementsByName but it didn't worked. my code is like that. can anyone help me please?

<form>
<input type="radio" name="question1" value="1" id="q1"> true
<input type="radio" name="question1" value="0" id="q1"> false
</form>
<button onclick="myFunction()">try</button>

<script>
function myFunction()
{
var x=document.getElementsByName("question1").value;
window.alert("your score is " +x);
}
</script>

Upvotes: 0

Views: 717

Answers (1)

Teemu
Teemu

Reputation: 23386

Radio buttons grouped by name behave differently from select element, i.e. the group hasn't a single value. Also getElementsByName() returns a HTMLCollection, which is an array-like object (see Felix Kling's comment).

I'd suggest you to do something like this (after giving an idto the form):

function myFunction () {
    var form = document.getElementById('form'), // a reference to the form element
        question = form['question1'], // creates a HTMLCollection from elements having attribute name="question1"
        n; // loop index
    for (n = 0; n < question.length; n++) { // iterates through items in HTMLCollection
        if (question[n].checked) { // checks the current item's 'checked' property
            alert("your score is " + question[n].value); // found the checked-one
            break; // "checked" found, no need to search more
        }
    }
}

A live demo at jsFiddle.

Bracket notation in question definition is used for future purposes. Just in case you'd have more radio button groups, which could be handled with this same function, you can pass the name of the group to function, and then use that argument within brackets instead of literal value ('question1').

Upvotes: 1

Related Questions