Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't empty array between submits

I'v been struggling with this problem for quite long now. I have an array where I'll be pushing numbers on button click to array like [2,6,8]. I tried emptying the array between submits with another button click but I'm unsuccessful. Can someone point out my mistake? The array keeps printing the first result even if I try to format and change it many times after that. The data-index also changed correctly in the DOM. I tried to empty the array also at the start of #accept click, but with no effect.

var mediaArray = [];

$( "#clearAll" ).click(function() {
        mediaArray = [];
        console.log("i can see this");
});

$( "#accept" ).click(function() {
        var firstRound = true;
        var mediaLength = 0;
        var eachData = 0;
        $( ".slots" ).each(function(index) {
            if (!firstRound) {
                mediaLength++;
                if ($(this).data('index') != eachData) {
                    mediaArray.push(mediaLength);
                    mediaLength = 0;
                }
            }
            eachData = $(this).data('index');
            firstRound = false;
            console.log($(this).data('index'));
        });
        mediaArray.push(mediaLength+1);

        console.log(mediaArray);
});
like image 571
Jack M. Avatar asked Dec 30 '25 08:12

Jack M.


1 Answers

that's pretty simple. It is due to your firstRound being true every time the click handler is invoked.

To fix it, you might want to have firstRound as a global variable, but that usually is not desired, in which case you can use an IIFE to make it local:

(function() {

    var firstRound = true;

    $( "#accept" ).click(function() {
        // ...
    });

}());
like image 134
nonopolarity Avatar answered Jan 01 '26 00:01

nonopolarity