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

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?

This question is related to javascript html forms html-input

The answer is


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;
}

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.


You need onSubmit. Not onClick otherwise someone can just press enter and it will bypass your validation. As for canceling. you need to return false. Here's the code:

<form onSubmit="return btnClick()">
<input type='submit' value='submit request'>

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

Edit onSubmit belongs in the form tag.


This is a very old thread but it is sure to be noticed. Hence the note that the solutions offered are no longer up to date and that modern Javascript is much better.

<script>
document.getElementById(id of the form).addEventListener(
    "submit",
    function(event)
    {
        if(validData() === false)
        {
            event.preventDefault();
        }
    },
    false
);

The form receives an event handler that monitors the submit. If the there called function validData (not shown here) returns a FALSE, calling the method PreventDefault, which suppresses the submit of the form and the browser returns to the input. Otherwise the form will be sent as usual.

P.S. This also works with the attribute onsubmit. Then the anonymus function function(event){...} must in the attribute onsubmit of the form. This is not really modern and you can only work with one event handler for submit. But you don't have to create an extra javascript. In addition, it can be specified directly in the source code as an attribute of the form and there is no need to wait until the form is integrated in the DOM.


With JQuery is even more simple: works in Asp.Net MVC and Asp.Core

<script>
    $('#btnSubmit').on('click', function () {

        if (ValidData) {
            return true;   //submit the form
        }
        else {
            return false;  //cancel the submit
        }
    });
</script>

<input type='button' onclick='buttonClick()' />

<script>
function buttonClick(){
    //Validate Here
    document.getElementsByTagName('form')[0].submit();
}
</script>

You need to return false;:

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

function btnClick() {
    return validData();
}

It's simple, just return false;

The below code goes within the onclick of the submit button using jquery..

if(conditionsNotmet)
{
return false;
}

use onclick='return btnClick();'

and

function btnClick() {
    return validData();
}

Sometimes onsubmit wouldn't work with asp.net.

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" />
   </div>
   <input type="submit" value="login" id="login-btn"/>
</form>

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) {
                event.preventDefault();
                alert("do what ever you want");
            });
 });

You need to change

onclick='btnClick();'

to

onclick='return btnClick();'

and

cancelFormSubmission();

to

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).


Why not change the submit button to a regular button, and on the click event, submit your form if it passes your validation tests?

e.g

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

function btnClick() { 
    if (validData()) 
        document.myform.submit();
} 

function btnClick() {
    return validData();
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to forms

How do I hide the PHP explode delimiter from submitted form results? React - clearing an input value after form submit How to prevent page from reloading after form submit - JQuery Input type number "only numeric value" validation Redirecting to a page after submitting form in HTML Clearing input in vuejs form Cleanest way to reset forms Reactjs - Form input validation No value accessor for form control TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

Examples related to html-input

Using Pipes within ngModel on INPUT Elements in Angular HTML 5 input type="number" element for floating point numbers on Chrome Html/PHP - Form - Input as array How to locate and insert a value in a text box (input) using Python Selenium? Drop Down Menu/Text Field in one HTML5 pattern for formatting input box to take date mm/dd/yyyy? How to add button inside input How to handle floats and decimal separators with html5 input type number How to set default value to the input[type="date"] Get data from file input in JQuery