1

I have a quiz I am making.

Some questions have multiple answers.

My html is as:

<div>Which problems equal 4?</div>
<input type="checkbox" id="qid" class="checks" data-correct="yes">2 + 2<br />
<input type="checkbox" id="qid" class="checks" data-correct="no">2 - 2<br />
<input type="checkbox" id="qid" class="checks" data-correct="yes">2 * 2<br />

I would like to alert if checked answers are both wrong or right.

Currently, my Javascript looks like this:

function checkMsResults(){
    var result = $('input[name="qid"]:checked').attr("data-correct");
    if(result == '1'){
        result = "Answer is Correct";
    }
    else if(result == '0'){
        result = "Answer is Not Correct";
    }
    else{
        result = "Please make a selection";
    }
    alert(result + ".");
}

This will alert only one selection. Can someone teach me how to loop through each on so I can alert multiple selections?

1
  • where are you calling the function 'checkMsResults' Commented May 4, 2015 at 18:37

2 Answers 2

3

You have three inputs with the same id, you can't do that, id must be unique.

function checkMsResults() {
  if ($('input[name="quid"]:checked').length === 0) {
    var result = "Please make a selection";
    alert(result);
    return;
  }
  $('input[name="quid"]:checked').each(function() {
    var result;
    if (this.getAttribute("data-correct") === "yes") {
      result = "Answer is Correct";
    } else {
      result = "Answer is Not Correct"
    }
    alert(result);
  });
}

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

2 Comments

The id's are actually php generated and are all different. I forgot to show the differences in the question.
I see that there is a .each that creates a loop for the if / else statement. Thank you, now I know.
1

Cleaned up your original. Here's a jsfiddle that takes the answer of each and sticks all into an array off answers; you can do whatever you want with it after that...https://jsfiddle.net/r2xc22Ld/1/

function checkMsResults(){


var result = "";
var answers = [];
$('input[name="qid"]:checked').each(function() {
   answers.push($(this).attr('data-correct'));
});

//console.log(answers);
for(var i = 0; i< answers.length; i++){
    result += 'Question '+i+': ' + answers[i] +'\n';   
}
if(result==""){
    alert('make a selection...');
}else{
    alert(result);
}

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.