0

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>
5
  • 1
    Hint: getElement s ByName. The method returns a set of elements. Have a look at the documentation: developer.mozilla.org/en-US/docs/Web/API/…. Commented Dec 20, 2013 at 22:07
  • an ID can be shared by two or more elements in the same page. change second radio id. Commented Dec 20, 2013 at 22:12
  • Umm.. How can I get the value of 'question1'? When I use 'getElementById' it shows '1' in either way. Commented Dec 20, 2013 at 22:13
  • you need to change the ID of radio buttons..ID has to be unique. Giveq1 and q2 as ID's Commented Dec 20, 2013 at 22:19
  • Okay, I got it. I changed id's as q1 and q2. But now how can I define 'x' variable as a 1 or 0 with using radio buttons? Commented Dec 20, 2013 at 22:22

1 Answer 1

1

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

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

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.