'How to reset recursive function in JS?
I have a function to follow the multistep form:
function multistep() {
function disableBtn() {
continueButton.attr('disabled', true);
}
let select = $('.cf7mls_current_fs select');
let continueButton = $('.cf7mls_current_fs .cf7mls_next');
$('.wpcf7-submit').attr('disabled', false);
$('.preloader-form-wrap').hide();
$('.select-choosen').each(function () {
$(this).removeClass("select-choosen");
});
let selectArr = [];
let currentArr = [];
select.each(function (i, obj) {
currentArr.push($(obj).attr("name"));
})
continueButton.attr('disabled', true);
select.on('change', function () {
if ($(this).prop('selectedIndex') !== 0) {
if ($(this).hasClass("select-choosen") === false) {
$(this).addClass("select-choosen");
selectArr.push($(this).attr("name"));
}
} else {
$(this).removeClass("select-choosen");
selectArr.shift();
disableBtn();
}
console.log(selectArr.length, currentArr.length);
if (selectArr.length === currentArr.length) {
continueButton.attr('disabled', false);
$(continueButton).on("click", function () {
selectArr = [];
$('.preloader-form-wrap').show();
setTimeout(() => {
// if is everything ok, runs function again!
// but array from above will not be reset
multistep();
}, 1000);
});
}
});
}
And the goal of the function is to enable button if every step is filled, and this works, but I have a problem with
let selectArr = [];
When a function calls itself, the inner, variable from (array) above will not be reset? And function will be called multiple times.
First time call function:
$('.btn-open-form').click(function (e) {
....
multistep();
}
And reset again:
function closeForm() {
$(document).click(function (e) {
if ((e.target.className === "overlay-mobile form-active") == true
) {
multistep();
}
}
Function from above will be called on document init.
Well, let selectArr = []; if an array of choosing select items in one tab, and important is to have the length of the array above be equal to a number of displayed selected items.
If the length is the same, the button will be enabled, to jump on another tab.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
