0

I want to prevent a form from being submitted and I found this answer.
How can I listen to the form submit event in javascript?

This is the code

var checkForm = document.getElementById("check");

if(checkForm.addEventListener) {
    checkForm.addEventListener("submit", submitFunc, false);
}else if(checkForm.attachEvent) {
    checkForm.attachEvent("onsubmit", submitFunc);
}

function submitFunc() {
    document.querySelector("#check").addEventListener("submit", function(e) {
        e.preventDefault();
    });
}

This does not work, it calls the function on submit but it still submits the form. However, if I move this part out of the function it works and it stops the form from being submitted.

document.querySelector("#check").addEventListener("submit", function(e) {
        e.preventDefault();
});

But it was to my understanding that this part should go inside the callback function, it also seems more "correct" for this relevant code to go inside the relevant function. How come it doesn't work inside the function? Do I need to inject something in to the callback function to get it to work?

Ecaz
  • 111
  • 2
  • 12
  • Your first script adds an `submit` handler which itself adds another `submit` handler which would then stop the submission O.o – Andreas Feb 21 '18 at 09:52
  • A good sanity check is this: it very often is a conceptual error when you assign an event handler within an event handler, even more when the event and target element are the same. Think about that. – trincot Feb 21 '18 at 09:53
  • So... you're adding a click event listener to `#check` that when it's clicked calls `submitFunc` which adds another click event listener to the same element? `submitFunc` should be `function submitFunc(e) { e.preventDefault(); }` – Andy Feb 21 '18 at 09:54
  • Ah, thank you Andy! I basically just followed the answer in the linked post which said that should go in the callback function. Never really dabbled with javascript until now but it did look quite odd. – Ecaz Feb 21 '18 at 10:01

1 Answers1

0

From Andy

So... you're adding a click event listener to #check that when it's clicked calls submitFunc which adds another click event listener to the same element? submitFunc should be function submitFunc(e) { e.preventDefault(); }

Ecaz
  • 111
  • 2
  • 12