'Where to add onsubmit to a form in Javascript

In my HTML I've got a form without an onsubmit event listener:

<form action="contact.php" method="post" id="contact">
    ...
    <input type="submit" value="Send" />
</form>

As a result, the form is always posted whenever I click the "Send" button. However, I'd like to validate the input first, so I'd like to attach an event listener and intercept the post. This is how I attach the event listener to the form:

window.onload = function() {
    function validate() {
        return window.confirm("Confirm");
    }
    var form = document.getElementById("contact");
    form.addEventListener("submit", validate);
}

While the event listener is being executed, if I go by above approach the form is always posted! However, if I make the validate() function global and use onsubmit="return validate();" in the <form> tag, then the form is only being submitted conditionally, as expected.

Why does this not work by adding the validate() function as above? It seems the false return value gets lost?



Solution 1:[1]

Modern event handling has a more complex API, it gives more flexibility but that comes at the cost of not being able to tie behaviour to a simple boolean result.

For your use case, you need to capture the event object:

function validate(ev) {

Then you can prevent the default action on it:

if (!confirm('Confirm')) {
    ev.preventDefault();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Quentin