ed1t ed1t - 7 months ago 59
Javascript Question

How can I listen to the form submit event in javascript?

I wanna write my own form validation javascript library and I've been looking on google how to detect if a submit button is clicked but all I found is code where you have to use onClick on

onSubmit="function()"
in html.

I would like to make this javascript so that I don't have to touch any html code like adding onSubmit or onClick javascript.

Answer

Writing event handlers in vanilla javascript can be annoying to make work across browsers, so I'd recommend using a library like jquery to make it robust (and also easier to write).

In jquery, if you have a form like this:

<form id="hello-world" action="sayhello">
    <input type="submit" value="Hello!">
</form>

You can attach an event handler like this:

$('#hello-world').submit(function(ev) {
    ev.preventDefault(); // to stop the form from submitting
    /* Validations go here */
    this.submit(); // If all the validations succeeded
});