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);
});
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() {
// ...
});
}());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With