Slider Quiz adds previous quiz attempts to the bottom of the slide. (Slick SLider)

I took over a project that was developed a couple of years ago and I believe halfway finished. (Or really… the specifications changed)
So I have a quiz in which the user gets three attempts to pass the quiz. After they fail the first time, their results end up being added to the bottom of the slide.

I think it’s the AJAX and JSON holding onto the data. Is there a way to put something into my if statement that clears out the attempt if they fail?

The bold code below is my if failed statement. I am not great at AJAX 🙁
thanks in Advance and please let me know if I missed any code that is helpful to solve.

Screen Shot

Code:

var count = 0;
let quizbutton2 = $('.btn, .btn-lesson-quiz');
function saveQuizData(event, isPreQuiz) {
    var res = [];
    event.closest('.pre-quiz-question').querySelectorAll('#quiz input:checked').forEach(function (e) {
        var UserQuizViewModel = new Object();
        UserQuizViewModel.CourseQuizID = event.closest('.pre-quiz-question').querySelectorAll('#QuizID')[0].getAttribute('value');//$("#LessonQuizID").val();
        UserQuizViewModel.QuizQuestionID = e.getAttribute('name');
        UserQuizViewModel.QuizAnswer = e.getAttribute('value');
        res.push(UserQuizViewModel)
    });
    var parentElem = event.closest(".pre-quiz-question");


    if (!isPreQuiz) {
        var allInputs = event.closest('.pre-quiz-question').querySelectorAll('input');
        var arr = [];
        getAllElementsWithAttribute('required', allInputs).map(x => {
            var obj = new Object();
            obj.name = x.name;
            obj.checked = x.checked;
            obj.value = x.defaultValue;
            arr.push(obj)
        })

        var selectedItems = arr.filter(x => { return x.checked === true }).filter((v, i, a) => a.findIndex(v2 => (v2.name === v.name)) === i).map(x => x.name);
        var noSelectedItems = arr.filter((v, i, a) => a.findIndex(v2 => (v2.name === v.name)) === i).map(x => x.name).filter(x => !selectedItems.includes(x))

        if (selectedItems && selectedItems.length > 0) {
            selectedItems.map(x => {
                $('.quiz-error-' + x).removeClass('error-active');
            })
        }

        if (noSelectedItems && noSelectedItems.length > 0) {
            noSelectedItems.map(x => {
                $('.quiz-error-' + x).addClass('error-active');
            })

            if (count == 0) {
                var setHeight = $('.slick-list').css("height");
                if (noSelectedItems.length >= 1) {
                    $('.slick-list').css("height", (parseInt(setHeight.substring(0, setHeight.length - 2)) + noSelectedItems.length * 18));
                }
            }
             
            //$('.slick-list').css("height", "max-content");     
            scrollToElem(event.closest('.pre-quiz-question').querySelector('.error-active'), true);
            $('.slick-track').css("position", "sticky");         
        }
    }
    else {
        var noSelectedItems = [];
    }

    if (noSelectedItems.length === 0) {
        if (res && res != null && res.length > 0) {
            res = JSON.stringify({ 'userQuizAttempt': res });
            event.disabled = true;
            scrollToElem(document.querySelector('.slidebox'), false);
            $.ajax({
                type: "POST",
                url: "/coursequiz/quizattempt",
                data: res,
                contentType: "application/json; charset=utf-8",
            }).done(function (result) {
                console.log(result);
                var setHeight = $('.slick-list').css("height");
                if (count == 0 && noSelectedItems.length >= 1) {
                    $('.slick-list').css("height", (parseInt(setHeight.substring(0, setHeight.length - 2)) + noSelectedItems.length * 18))
                }

                if (event.closest('.pre-quiz-question').previousElementSibling && event.closest('.pre-quiz-question').previousElementSibling.className.includes('quiz-score')) {
                    event.closest('.pre-quiz-question').previousElementSibling.style.display = "none";
                }
                else {
                    $('.slick-list').css("height", (parseInt(setHeight.substring(0, setHeight.length - 2)) + 40))
                }

                if (result.includes('quiz-passed')) {
                    parentElem.insertAdjacentHTML('afterend', result);
                    //parentElem.remove();
                    $('.next-bottom').show();
                     $('.next-top').show();
                    event.disabled = false;
                    alert ("You have passed! Please click the next button to continue with the course.");
                    $("#score-top").css("height","50px");
                    location.reload();
                }
                

         **   else {
             
                    parentElem.insertAdjacentHTML('afterend', result);
                    showMessage();
                   event.disabled = false; 
                   $(quizbutton2).prop('disabled', true); 
                }
                **
            
                //if (isPreQuiz) {
                   // parentElem.remove();
               // }
                //scrollToElem(document.querySelector('.slidebox'), false);
                //$('.slick-list').css("height", "max-content");
   
            }).fail(function (xhr) {
                console.log('error : ' + xhr.status + ' - ' + xhr.statusText + ' - ' + xhr.responseText);
            });;
            $.ajax({
                type: "POST",
                url: "/coursequiz/getcorrectanswers",
                data: res,
                contentType: "application/json; charset=utf-8"
            }).done(function(result) {
                var correctAnswers = result.CorrectAnswers;

                if(document.querySelectorAll('.correct-answer').length){
                    var classes = document.querySelectorAll('.correct-answer');
                    for(i = 0; i < classes.length; i++){
                       classes[i].classList.remove('correct-answer')
                    }
                }

                if(document.querySelectorAll('.incorrect-answer').length){
                    var classes = document.querySelectorAll('.incorrect-answer');
                    for(i = 0; i < classes.length; i++){
                        classes[i].classList.remove('incorrect-answer')
                    }
                }

                if(document.querySelectorAll('.slick-current input[type="radio"]:checked, input[type="checkbox"]:checked').length){
                    for(i = 0; i < document.querySelectorAll('.slick-current input[type="radio"]:checked, input[type="checkbox"]:checked').length; i++){
                        if(document.querySelectorAll('.slick-current input[type="radio"]:checked, input[type="checkbox"]:checked')[i].value.includes(correctAnswers[i])){
                            document.querySelectorAll('.slick-current input[type="radio"]:checked + label, input[type="checkbox"]:checked + label')[i].classList.add('correct-answer');
                        } else{
                            document.querySelectorAll('.slick-current input[type="radio"]:checked + label, input[type="checkbox"]:checked + label')[i].classList.add('incorrect-answer');
                        }
                    }
                }

            }).fail(function(xhr) {
                console.log('error : ' + xhr.status + ' - ' + xhr.statusText + ' - ' + xhr.responseText);
            });
        }
    }
    count++;
}

We found the answer. My awesome coworker helped me figure this out. As part of the JSON request, it was rebuilding the entire HTML on the slide. We commented the function out and it solved the issue.

Leave a Comment