I am flabbergasted trying to figure out a way to prevent the button click from rendering multiple times based on the number of clicks. If you I click "submitButton" once, everything runs once. If I click it a second time, everything runs twice. If I click it a third time, everything runs three times... And so on...
Here is the code I am running to initiate the running of several functions. The subsequent functions grab data from a database, creates batches of 100, then inserts that data into an HTTP POST request.
submitButton.addEventListener("click", () => {
if (document.getElementById("subject").value == "") {
alert(
"Please add a Subject for your Push Notification before sending."
);
} else if (document.getElementById("body").value == "") {
alert(
"Please add a Message Body for your Push Notification before sending."
);
} else if (
document.querySelectorAll("input[type=radio]:checked").length < 1
) {
alert("Please select a Jump-To page before sending.");
} else {
btn.classList.add("button--loading");
submitButton.disabled = true;
SelectData();
}
});
Following SelectData(); are the functions that batch, create and send the HTTP POST request. At the end of all of this, I've attempted to add the following to prevent some type of storage of EACH click event, operating under the assumption that is my problem. That is, that each click is being stored locally in the browser, and thus if number of clicks = 2 then SelectData(); will run twice along with all other functions related to the click event.
submitButton.removeEventListener("click", null);
submitButton.disabled = false;
I was hopeful the above would be my answer, but it has not done anything differently. I'd love some help and am happy to provide more specifics if necessary, but i am stumped. I appreciate your help in pointing me in the right direction!
The second argument for removeEventListener must be exactly the function provided to addEventListener
function myOnClickFunc() {
console.log("oh jolly, a click!")
}
myElement.addEventListener("click", myOnClickFunc)
myElement.removeEventListener("click", myOnClickFunc) // note the exact same object is passed
This would probably fix it. Though it is preferable for you to rewrite your code in a way where you use the same event listener repeatedly instead of removing and readding it.