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

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

I’m working on an web application.
I have a form with a submit button. The code for the submit button looks like .
I want to write something like the following:
function btnClick() {
if (!validData())

How do I do this?


Solution 1:

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();

Solution 2:

Change your input to this:

<input type='submit' value='submit request' onclick='return btnClick();'>

And return false in your function

function btnClick() {
    if (!validData())
        return false;

Solution 3:

You need to change



onclick='return btnClick();'




return false;

That said, I’d try to avoid the intrinsic event attributes in favour of unobtrusive JS with a library (such as YUI or jQuery) that has a good event handling API and tie into the event that really matters (i.e. the form’s submit event instead of the button’s click event).

Solution 4:

Sometimes onsubmit wouldn’t work with

I solved it with very easy way.

if we have such a form

<form method="post" name="setting-form" >
   <input type="text" id="UserName" name="UserName" value="" 
      placeholder="user name" >
   <input type="password" id="Password" name="password" value="" placeholder="password" >
   <div id="remember" class="checkbox">
    <label>remember me</label>
    <asp:CheckBox ID="RememberMe" runat="server" />
   <input type="submit" value="login" id="login-btn"/>

You can now catch get that event before the form postback and stop it from postback and do all the ajax you want using this jquery.

$(document).ready(function () {
            $("#login-btn").click(function (event) {
                alert("do what ever you want");

Solution 5:

you should change the type from submit to button:

<input type='button' value='submit request'>

instead of

<input type='submit' value='submit request'>

you then get the name of your button in javascript and associate whatever action you want to it

var btn = document.forms["frm_name"].elements["btn_name"];
btn.onclick = function(){...};

worked for me
hope it helps.

Solution 6:

You need to return false;:

<input type='submit' value='submit request' onclick='return btnClick();' />

function btnClick() {
    return validData();