0

I'm developing an app about quizzes.

IMG1: [The added comments in this picture applies for the IMG2 too]

enter image description here

IMG2:

enter image description here

Description:

[IMG1] When one or more .js-answer-check checkbox are checked, I save the values in a js array. Then, when the #save-response button is clicked, the respective array is send to the server, to be saved in the db.

[IMG2] Then I click another question of the quiz, identified by .quiz-questions class, and when one or more .js-answer-check checkboxes of this new question are checked, the values are saved in the same js array.

The problem is that the previous checkboxes values, from the previous answers, are still present in the array, due to that answers.push(answerID).

How can I only grab the values of the respective question answers in the array each time a .quiz-questions button is clicked?

Expected values:

  1. clicking the checkbox with label "2" in the first question => array should be [ 2 ] (the data-id="2" attribute in that checkbox)
  2. clicking the checkboxes with label "1+3" and "8/2" in the second question => array should be [4, 5] as those checkboxes have data-id="4" and data-id="5" attributes.

Actual result: [2, 4, 5]

I tried out this code:

//if one|more options are checked...
var answers = [];
$(document).on('click', '.js-answer-check', function(){
    if ($(this).is(':checked')){
        var answerID = $(this).data('id');
        answers.push(answerID);
    } else {
        var removeItem = $(this).data('id');
        answers = $.grep(answers, function(value){
            return value != removeItem;
        });
    }
});

$('#save-response').on('click', function(e){
    e.preventDefault();
    $.ajax({
        method: 'POST',
        url: Routing.generate('save_answer'),
        data: { answers: answers },
        success: function(resp) {
            if (resp.success) {
                var answersBack = resp.answers;
                for (var ans in answersBack) {
                    console.log('answerID = ', answersBack[ans]);
                }
            }
            //answers = [];
        }
    });
});

And I thought that if I do answers = [] will reset the initial array, but it didn't.

Any help is welcomed. Thanks.

LATER EDIT

<div class="row margin-top-ten">
    <div class="col-6">
        <input type="hidden" id="quiz-id" data-quiz="{{ quiz.id }}"/>
        <div class="row question-content">{# the content (question-text + checkboxes) is coming from an AJAX request because I need to present everytime a new content based on `quiz-questions` buttons #}
        </div>
    </div>
</row>

<div class="row margin-top-ten">
    <div class="col-12">
        <button class="btn btn-primary btn-sm" type="button" id="save-response">Salveaza</button>
    </div>
</div>

<div class="row margin-top-fifty">
    <div class="col-12">
        {% set i = 1 %}
        <p>Navigator intrebari:</p>
        {% for question in quiz.questions %}
            <a href="" class="btn btn-info btn-sm quiz-question"
                               data-id="{{ question.id }}" data-quiz="{{ quiz.id }}">
                {{ i }}
            </a>
            {% set i = i + 1 %}
        {% endfor %}
    </div>
</div>

The AJAX request for bringing new content for each quiz-questions buttons is:

<div class="col-12">
    <div class="row">
        <div class="col-12 question-text" data-question="{{ question.id }}">{{ question.content|raw }}</div>
    </div>
    <div class="row">
        {% for answer in question.answers %}
            <div class="col-12 question-answers">
                <span style="display: inline-block">
                    <label for="">
                        <input type="checkbox" name="user-responses[]" class="js-answer-check" data-question="{{ question.id }}" data-id="{{ answer.id }}">
                    </label>
                </span>
                <span style="display:inline-block">{{ answer.answer|raw }}</span>
            </div>
        {% endfor %}
    </div>
</div>

The save_answer php functionality is just returning the sent-data, for debug purposes. Nothing fancy.

Dan Costinel
  • 1,716
  • 1
  • 15
  • 23
  • resetting the answers array should be doing the trick. That's the only thing I can come up with. But why aren't you just submitting the form with ajax? Then you don't have to keep track of a list of selected items, because the html form will do that for you. – Leroy May 06 '18 at 14:34
  • @Leroy I'm already sending the answers through AJAX. – Dan Costinel May 06 '18 at 14:39
  • Please provide relevant html instead of images as per [mcve] so others can test your code – charlietfl May 06 '18 at 14:41
  • Ok @charlietfl, check my later edit. Thanks – Dan Costinel May 06 '18 at 14:55
  • So, according to [this](https://stackoverflow.com/a/1232046/4548751) answer, all I needed to do is, instead of `answers = []`, it should be `answers.length = 0`. – Dan Costinel May 06 '18 at 15:21
  • As noted in first section of that linked answer , overwriting with new empty array vs empting existing one really depends on whether you have other references elsewhere to the original array that would be broken. I suspect in your case you don't – charlietfl May 06 '18 at 16:35
  • @charlietfl No, I don't use the `answers` array elsewhere. This is used just for grabbing the `data-id`s from each question answers checkboxes. – Dan Costinel May 06 '18 at 16:38

0 Answers0