4

I've created a step by step test (fiddle example below) that doesn't quite tally up the total correctly. It works fine if all questions have one answer but when there's multiple answers for a single question it gives a strange tally.

(All answers to the questions are the first checkbox except for "Question 2", the multiple choice question, which is the first 2 checkboxes)

For the multiple choice question - the progress squares at the bottom change green when only one of the two answers is correct (when you click next), it should only be green when both are checked correctly, if not correct then it should be red.

The second issue is that if you answer all questions correctly then the final score is 7... when it should be 5 (multiple choice questions should add 1 point per answer). (If you inspect the fiddle, you can see the total being updated when the next button is clicked in the hidden field at the bottom)

Where am I going wrong?

http://jsfiddle.net/rob_teamworks/vebcsjw0/

jQuery(function($) {
$(document).ready(function() {

  // hide all form-rows, but not the first one
  $('.form-row').not(':first').hide();

  // hide on last step
  $('button.next').last().hide();

var score = 0;
  $('button.next, input.check').click(function(e) {
    // prevent the next buttons from submitting the form
    e.preventDefault();

		var item = $(this).parents('div.form-row').find('.correct:first').data('progress');
    if ($(this).parents('div.form-row').find('.correct:first').is(":checked") && $(this).parents('div.form-row').find('.correct:first').hasClass('correct-answer')) {
			$('.quiz-progress-circle[data-progress="' + item + '"]').removeClass("progress-incorrect");
			$('.quiz-progress-circle[data-progress="' + item + '"]').addClass("progress-correct");
			score += Number(score+1);
		} else {
			$('.quiz-progress-circle[data-progress="' + item + '"]').removeClass("progress-correct");
      $('.quiz-progress-circle[data-progress="' + item + '"]').addClass("progress-incorrect");
    }

    // hide this form-row, and show the next one
    $(this).parents('div.form-row').hide().next('div.form-row').show();
		$('.finalscore').val(score);
	});

	// add the submit button to the last form-row
  $('<input>').addClass('check').prop('type', 'submit').appendTo($('.form-row:last'));

});
});


jQuery(function($) {
$(document).ready(function () {
    $("input[type=checkbox].correct").click(function (e) {
        if ($(e.currentTarget).closest("div.question").length > 0) {
            toggleInputs($(e.currentTarget).closest("div.question")[0]);
        }
    });
});

function toggleInputs(questionElement) {
    if ($(questionElement).data('max-answers') == undefined) {
        return true;
    } else {
        maxAnswers = parseInt($(questionElement).data('max-answers'), 10);
        if ($(questionElement).find(".correct:checked").length >= maxAnswers) {
            $(questionElement).find(".correct:not(:checked)").attr("disabled", true);
        } else {
            $(questionElement).find("input[type=checkbox].correct").attr("disabled", false);
        }
    }
}
});
.quiz-progress-circle {
	height:5px;
	width:5px;
	background-color:grey;
	display:inline-block;
	margin-right:10px;
}

.progress-correct {
	background-color:green!important;
}

.progress-incorrect {
	background-color:red!important;
}

.progress-current {
	background-color:blue!important;	
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<section class="row test">
				<div class="columns">
					<div class="entry">

						<form class="form" method="POST" action="http://example.com/test-insert.php">
							
							<input type="hidden" value="teamworks" name="test-user">
							<input type="hidden" value="Introduction" name="test-name">

														<div class="form-row">
								<h1>Quiz | Introduction</h1>

								<div class="clear"></div>
								<div id="module-area">
									<div id="modules-top"></div>
									<div id="modules-repeat">
											<h2 class="training">1. Question 1</h2>

											<div class="question" data-max-answers="1">
																																				<div style="display:table-row;">
														<div style="display:table-cell;">
															<input class="correct correct-answer" data-progress="1" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 1">
														</div>
														<div style="display:table-cell;">
															<p>
																Answer 1															</p>
														</div>
													</div>
																																					<div style="display:table-row;">
														<div style="display:table-cell;">
															<input class="correct " data-progress="1" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 2">
														</div>
														<div style="display:table-cell;">
															<p>
																Answer 2															</p>
														</div>
													</div>
																																					<div style="display:table-row;">
														<div style="display:table-cell;">
															<input class="correct " data-progress="1" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 3">
														</div>
														<div style="display:table-cell;">
															<p>
																Answer 3															</p>
														</div>
													</div>
																							</div>
											<div class="inner"></div>
											<button class="next">Next &gt;&gt;</button>
										<div class="clear"></div>
									</div>
									<div id="modules-bottom"></div>
								</div>
							</div>
														<div class="form-row" style="display: none;">
								<h1>Quiz | Introduction</h1>

								<div class="clear"></div>
								<div id="module-area">
									<div id="modules-top"></div>
									<div id="modules-repeat">
											<h2 class="training">2. Question 2</h2>

											<div class="question" data-max-answers="2">
																																				<div style="display:table-row;">
														<div style="display:table-cell;">
															<input class="correct correct-answer" data-progress="2" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 1">
														</div>
														<div style="display:table-cell;">
															<p>
																Answer 1															</p>
														</div>
													</div>
																																					<div style="display:table-row;">
														<div style="display:table-cell;">
															<input class="correct correct-answer" data-progress="2" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 2">
														</div>
														<div style="display:table-cell;">
															<p>
																Answer 2															</p>
														</div>
													</div>
																																					<div style="display:table-row;">
														<div style="display:table-cell;">
															<input class="correct " data-progress="2" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 3">
														</div>
														<div style="display:table-cell;">
															<p>
																Answer 3															</p>
														</div>
													</div>
																							</div>
											<div class="inner"></div>
											<button class="next">Next &gt;&gt;</button>
										<div class="clear"></div>
									</div>
									<div id="modules-bottom"></div>
								</div>
							</div>
														<div class="form-row" style="display: none;">
								<h1>Quiz | Introduction</h1>

								<div class="clear"></div>
								<div id="module-area">
									<div id="modules-top"></div>
									<div id="modules-repeat">
											<h2 class="training">3. Question 4</h2>

											<div class="question" data-max-answers="1">
																																				<div style="display:table-row;">
														<div style="display:table-cell;">
															<input class="correct correct-answer" data-progress="3" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 1">
														</div>
														<div style="display:table-cell;">
															<p>
																Answer 1															</p>
														</div>
													</div>
																																					<div style="display:table-row;">
														<div style="display:table-cell;">
															<input class="correct " data-progress="3" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 2">
														</div>
														<div style="display:table-cell;">
															<p>
																Answer 2															</p>
														</div>
													</div>
																																					<div style="display:table-row;">
														<div style="display:table-cell;">
															<input class="correct " data-progress="3" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 3">
														</div>
														<div style="display:table-cell;">
															<p>
																Answer 3															</p>
														</div>
													</div>
																							</div>
											<div class="inner"></div>
											<button class="next">Next &gt;&gt;</button>
										<div class="clear"></div>
									</div>
									<div id="modules-bottom"></div>
								</div>
							</div>
														<div class="form-row" style="display: none;">
								<h1>Quiz | Introduction</h1>

								<div class="clear"></div>
								<div id="module-area">
									<div id="modules-top"></div>
									<div id="modules-repeat">
											<h2 class="training">4. Question 5</h2>

											<div class="question" data-max-answers="1">
																																				<div style="display:table-row;">
														<div style="display:table-cell;">
															<input class="correct correct-answer" data-progress="4" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 1">
														</div>
														<div style="display:table-cell;">
															<p>
																Answer 1															</p>
														</div>
													</div>
																																					<div style="display:table-row;">
														<div style="display:table-cell;">
															<input class="correct " data-progress="4" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 2">
														</div>
														<div style="display:table-cell;">
															<p>
																Answer 2															</p>
														</div>
													</div>
																																					<div style="display:table-row;">
														<div style="display:table-cell;">
															<input class="correct " data-progress="4" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 3">
														</div>
														<div style="display:table-cell;">
															<p>
																Answer 3															</p>
														</div>
													</div>
																							</div>
											<div class="inner"></div>
											<button class="next" style="display: none;">Next &gt;&gt;</button>
										<div class="clear"></div>
									</div>
									<div id="modules-bottom"></div>
								</div>
							<input class="check" type="submit"></div>
							


							<div class="quiz-progress">
																	<div class="quiz-progress-circle" data-progress="1"></div>
																	<div class="quiz-progress-circle" data-progress="2"></div>
																	<div class="quiz-progress-circle" data-progress="3"></div>
																	<div class="quiz-progress-circle" data-progress="4"></div>
															</div>


							<input type="hidden" value="236" name="test-id">
							<input class="finalscore" type="hidden" value="" name="test-score">
							<input type="hidden" value="2" name="test-pass">

						</form>



						<div class="clear"></div>
				</div>


			    </div>
		    </section>

This is the php file it calls on submit. The variable $score comes from the hidden field with the name test-score that is tallied up by the jquery variable score.

<?php
$score = $_POST["test-score"];


$pass_msg = $_POST["test-pass"];
if ($score >= $pass_msg) {
    $pass_txt = "Pass";
} else {
    $pass_txt = "Fail";
}

// Opens a connection to a MySQL server
$username="root";
$password="root";
$database="local";
$host="localhost";

$con = mysqli_connect($host, $username, $password);
if (!$con)
{
    die('Could not connect: ' . mysqli_error());
}
mysqli_select_db($con, "local");
$user = $_POST["test-user"];
$testid = $_POST["test-id"];
$sql = mysqli_query($con, "INSERT INTO test (`name`, `testname`, `score`, `pass-fail`) VALUES ('".$user."', '".$testid."', '".$score."', '".$pass_txt."')");
if (!$sql)
  {
  die('Error: ' . mysqli_error());
  }
mysqli_close($con);
header('Location: http://example.com/training/introduction/');
?>

Thanks to @viorel for the answer, it's caused an additional problem:

It should only show the second submit button on the last question... it should submit the form but it's not counting the question towards the score.

8
  • 1
    Warning: Your code is vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. Never insert unsanitised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data.
    – ADyson
    Apr 25, 2019 at 15:50
  • Never get your web app to login to the database as root. Root can do whatever it likes, so on top of the SQL injection vulnerabilities this just leaves your database an open book for hackers. Instead create a separate user account specifically for this application which has only the permissions it actually needs in order to work properly. Don't even use the root account as a shortcut during development or testing, because you need to test your account permissions as well - otherwise when you go live you might have unexpected errors relating to the user account setup.
    – ADyson
    Apr 25, 2019 at 15:50
  • 1
    @ADyson It's my local environment so it won't be logging in as root when it goes live. As for the rest, I'll deal with that later.
    – Rob
    Apr 25, 2019 at 15:53
  • Ok, but it's still a risk IMO...did you read the last sentence of my second comment about testing your permissions?
    – ADyson
    Apr 25, 2019 at 16:04
  • 1
    @ADyson Ok thanks for the heads up. I'll look into it after solving this question.
    – Rob
    Apr 26, 2019 at 8:05

2 Answers 2

2
+100

I've looked a little bit at the code and simplified the following bit:

$('button.next, input.check').click(function (e) {
    // prevent the next buttons from submitting the form
    e.preventDefault();

    var correctAnswers = $(this).siblings().find('.correct-answer').length;
    var totalUserCorrectAnswers = $(this).siblings().find('.correct-answer:checked').length;
    var totalCheckedAnswers = $(this).siblings().find('input:checked').length;

    var item = $(this).parents('div.form-row').find('.correct:first').data('progress');
    var resultBubble = $('.quiz-progress-circle[data-progress="' + item + '"]');

    if(correctAnswers === totalUserCorrectAnswers  && totalUserCorrectAnswers === totalCheckedAnswers) {
        resultBubble.removeClass("progress-incorrect");
        resultBubble.addClass("progress-correct");

        score += 1;
    } else {
        resultBubble.removeClass("progress-correct");
        resultBubble.addClass("progress-incorrect");
    }

    // hide this form-row, and show the next one
    $(this).parents('div.form-row').hide().next('div.form-row').show();
    $('.finalscore').val(score);
});

I've added three control variables: the total number of correct answers expected (correctAnswers), the number of correct answers the user selected (totalUserCorrectAnswers) and the total number of checked answers (totalCheckedAnswers). You may not need this last check since you are disabling the checkboxes.

For each steps, there's a simple check to see if the total number of answers selected equals the number expected. If they match, the score is incremented by one and the progress squares get the appropriate color. I couldn't figure out exactly the problem before, but it seems that you were only selecting the first correct checked answer

7
  • That's working, great thanks, moved it all forward! It's thrown up one error though, it's not counting the last question in the score. I answer it correctly but it doesn't count for some reason.
    – Rob
    Apr 30, 2019 at 13:35
  • 1
    What does the error say? I tested it in the fiddle here and it seems to count the correct answers: jsfiddle.net/ko6rzc5u In the last step, I pressed the button on the left button. The one on the right just submitted the form
    – kioleanu
    Apr 30, 2019 at 13:47
  • Think the first submit button is an error, it should only show the second one... it should submit the form but that's causing it not to count the last question.
    – Rob
    Apr 30, 2019 at 13:49
  • 1
    oh, that's because the actions are simultaneous. You need to wait in javascript until the answer has been checked. You can change the button to be of type="button", give it its own class, like <input class="check do-submit-after-check" type="button"> and then to a check: if($(this).hasClass('do-submit-after-check')) {$('form').trigger('submit'); } right after $('.finalscore').val(score);
    – kioleanu
    Apr 30, 2019 at 13:59
  • 1
    Got the problem. Here's an updated fiddle: jsfiddle.net/ko6rzc5u/1 . You should use on instead of click to delegate the event to the submit button. I also removed some redundant document ready listeners. Also, the button should be of type button, not submit. submit triggers the form
    – kioleanu
    Apr 30, 2019 at 14:25
0

To answer your second question,

score += Number(score+1);

This will add 2 each time, not 1. Change it to:

score++;

For your first question, your if function when button.next is clicked is true when only one answer is correct. A fix could be to define a variable (green = 1). And then run a jQuery Each for every .correct. In the Each Loop, if it has class correct answer but is not ticked, then change green to 0. Also, if a 'correct' with no 'correct-answer' is ticked then also update variable green to 0.

After the Each Loop, then use the value of the variable 'green' to determine if the progress square should be green or not.

3
  • That's actually the pass mark for the test, not the ongoing total as they go through the test. The ongoing total is the hidden field above.
    – Rob
    Apr 25, 2019 at 15:55
  • Yes you are right! Sorry, my mistake. I found the error: score += Number(score+1);This will add 2 each time, not 1. To fix this, just write score++
    – UKtoTaiwan
    Apr 25, 2019 at 15:58
  • It adds 1 to the tally but if you mark 1 right and 1 wrong on the multiple choice question it still awards the point. It needs to award it if both answers for the multiple choice are correct.
    – Rob
    Apr 26, 2019 at 9:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.