im trying to get my jquiz class to count for 2 IDs for each page.
It only counts the first page correctly. The second page just displays the same score as the first page. Im not sure what im doing wrong
This is what i have:
JQuery:
$(".jquiz li ul li").click(function()
{
var count1 = 0; //page1 counter
var count2 = 0; //page2 counter
//right answer
if ($(this).hasClass("correct"))
{
if ($("#page1"))
count1++; //page1
if ($("#page2"))
count2++; //page2
}
//page1 quiz counter display
if ($('ul.answered').length == 3)
{
$('#page1mark').fadeIn('slow');
$('#page1total').html('You got a '+count1+' out of '+3+' on the page1 quiz.');
}
//page2 quiz counter display
if ($('ul.answered').length == 6)
{
$('#page2mark').fadeIn('slow');
$('#page2total').html('You got a '+count2+' out of '+3+' on the page2 quiz.');
}
HTML: Note: the class jquiz is in the tag element OL. It wouldnt let me post the code
<id="page1" class="jquiz">
pizza is yum?
<Ii class ="correct"> true</Ii>
You’re going about it all wrong.
You should either be doing this whole code block for each quiz, localizing all selectors to that dom element, or you can do this in one event handler, but inside it find out what quiz was activated at the top first (using
jQuery.closest('.jquiz')), and limit everything else to within that dom node.Either way, it looks like each quiz has a different number of questions, so you should store the number of questions for each quiz in the dom, like this:
Then, here’s an example of the javascript updated with the first method I described above — setting up a separate callback for each quiz (I think the first method produces more readable code, and the efficiency cost is negligible here). This also incorporates the other above change I suggested:
Also, while not directly related to your question, this is worth noting. Looks like someone can just keep clicking on a correct item to increase their correct count indefinitely. Maybe instead of explicitly counting, just let the implicit count do the work. This is probably better even if the rest of your code prevents the possibility for such an incident: