How do I cancel form submission in submit button onclick event?

Vivian River picture Vivian River · Nov 19, 2010 · Viewed 280.8k times · Source

I'm working on an ASP.net web application.

I have a form with a submit button. The code for the submit button looks like <input type='submit' value='submit request' onclick='btnClick();'>.

I want to write something like the following:

function btnClick() {
    if (!validData())
        cancelFormSubmission();
}

How do I do this?

Answer

alex picture alex · Nov 19, 2010

You are better off doing...

<form onsubmit="return isValidForm()" />

If isValidForm() returns false, then your form doesn't submit.

You should also probably move your event handler from inline.

document.getElementById('my-form').onsubmit = function() {
    return isValidForm();
};