0

I have a form that I set up as a quiz to take. Eventually I will alter it to calculate the final score of the quiz once done. But I am stuck on this one part. I want to add a point if a right box is checked, and subtract a point if a wrong box is checked.

Code for a right answer:

<input type="checkbox" name="q3" id="q1javascript" answer="true">

Code for wrong answer:

<input type="checkbox" name="q3" id="q3xhtml" answer="false">

Javascript checking against it:

function test() {
    var boxes = document.getElementsbyName('q3');
    var score = 0;
    var i = 0;
    while (i < 4) {
        var answer = boxes[i].getAttribute('answer');
        if (answer === 'true') {
            score++;
        }
        else {
            score--;
        }
        i++;
    }
    alert(score);
}

JSFiddle

xjsc16x
  • 278
  • 1
  • 6
  • 16
  • Your jsfiddle can't work. Please fix it first. – pktangyue Mar 18 '13 at 04:01
  • Are your users inexperienced enough to not spot `answer="true"` in HTML? – zerkms Mar 18 '13 at 04:04
  • custom attributes are not valid, and if you are to use anything it would be in HTML5 and data-* attributes. Albeit invalid for other doctypes it is still the best way to go. – rlemon Mar 18 '13 at 04:04
  • 1
    DO you really want to keep an attribute in the html itself which says what the options are. It will be easy for a user to look at the html source to find out the answers for your questions. :) Probably you should think about it. – PSL Mar 18 '13 at 04:35

1 Answers1

2

Try this JSFiddle: http://jsfiddle.net/vCz2T/1/

The checkboxes now use data-answer="true" or data-answer="false". Any custom data like your answer attribute should be prefixed with data-:

<input type="checkbox" name="q3" id="q3css" data-answer="true">

The test() function has been changed to be:

function test() {
    var boxes = document.getElementsByName('q3');
    var score = 0;
    var i, box, answer;
    for (i = 0; i < boxes.length; i++) {
        box = boxes[i];
        if (box.checked) {
            answer = box.getAttribute('data-answer');
            if (answer === 'true') {
                score++;
            } else {
                score--;
            }
        }
    }
    alert(score);
}

You now have to do getAttribute('data-answer'). Also, you should check for box.checked so that only checked checkboxes are counted.

Tim Heap
  • 1,671
  • 12
  • 11
  • Almost there-- OP wanted the score to be incremented on a checkbox matching true, and decremented on a checkbox matching false. This solution doesn't do that. – Brian Rogers Mar 18 '13 at 04:28