简体   繁体   中英

Need quiz application to display only one item at a time

I have created a quiz application, I want the application to display one question at a time when the user sits the quiz. this worked fine until I populated the database with more than 5 questions now the quizzes displays all question could someone please tell me why this would be?

$(document).ready(function() {
    var steps = $('form').find(".questions");
    var count = steps.size();
    steps.each(function(i) {
        hider = i + count;

        if (count == i + 1) {
            var step = i + 1;
            $("#next" + step).on('click', submit);
        } else {
            $("#question_" + hider).hide();
            createNextButton(i);
        }

    });

    function submit() {
        $.ajax({
            type: "POST",
            url: "ajax.php",
            data: $('form').serialize(),
            success: function(msg) {
                $("#quiz_form,#demo1").addClass("hide");
                $('#result').show();
                $('#result').append(msg);
            }
        });
    }

    function createNextButton(i) {
        var step = i + 1;
        var step1 = i + 2;
        $('#next' + step).on('click', function() {
            $("#question_" + step).hide();
            $("#question_" + step1).show();
        });
    }
    setTimeout(submit, 50000);
});

PHP:

$response = $db->prepare("select * from questions WHERE test_ID = '" . $_POST['test_ID'] . "'");
$response->execute();

echo "<form method='post' id='quiz_form'>";

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$count = 1;

while($result=$response->fetch(PDO::FETCH_ASSOC)) {

For starters, your hider variable will always be +1 the size of your count. If you have a .size() of 5 questions, then (I would assume) the first iteration should hide, ie

hider = i + count
hider = 0 + 5
hider = 5
$("#question_5").hide();

If, however, you are generating your questions on the PHP end w/ zero indexing, then your last question (your 5th), should have the id of question_4 .

As you can see, your hider variable will never be less than 5, with each increment of

steps.each(function(i) {
   hider = i + count;
   ...
});

hider will only increment from 5, up to 10 (ie #question_10 ), which should not exist in your case.

I would imagine you could make things simpler by just using

$("#question_" + i).hide();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM