117

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?

2
  • ouch, this is making my head hurt. I have several different submit inputs. I think I'll try using server-side controls on this page. Commented Nov 19, 2010 at 16:39
  • 2
    possible duplicate of How to prevent form from being submitted?
    – T J
    Commented Sep 29, 2014 at 19:26

14 Answers 14

208

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();
};
8
  • Nice, but it seems that I can't get onsubmit to work whenever I'm using ASP.net because asp.net wraps EVERYTHING in it's own form... Commented Nov 19, 2010 at 16:30
  • 8
    You can use his second suggestion. Inline javascript is the devil anyway.
    – Stephen
    Commented Nov 19, 2010 at 16:32
  • 3
    If you are using ASP.NET web forms (hint: don't) then don't try to include other forms. They are simply incompatible. I hear ASP.NET MVC lets you build web apps using idiomatic markup.
    – Quentin
    Commented Nov 19, 2010 at 16:32
  • 1
    I have never used ASP.NET (not least because of all the problems I've seen people have trying to combine Web Forms with good markup and progressive enhancement) so I can't really comment.
    – Quentin
    Commented Nov 19, 2010 at 16:35
  • 2
    Someone else have answered EXACTLY like you stackoverflow.com/a/23604664/1639385. I think it was too much a coincidence. Commented Nov 10, 2015 at 11:54
48

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

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

1
  • 4
    Using onclick will allow the user to hit enter and bypass the check.
    – Cfreak
    Commented Nov 19, 2010 at 16:30
8

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");
            });
 });
6

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.

6

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.

0
4

You need to return false;:

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

function btnClick() {
    return validData();
}
4

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>
2

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();
} 
2
1

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.

1
  • this won't work. if data is valid you do not return true. put return true; at the end of btnClick() function
    – NickSoft
    Commented Nov 8, 2013 at 7:21
1

It's simple, just return false;

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

if(conditionsNotmet)
{
return false;
}
0

use onclick='return btnClick();'

and

function btnClick() {
    return validData();
}
1
  • 2
    hitting enter will bypass the check. Use onSubmit
    – Cfreak
    Commented Nov 19, 2010 at 16:29
0
function btnClick() {
    return validData();
}
4
  • 1
    It is necessary to do more than this to make it work. I've tried making the functino return true or false and it doesn't seem to make any difference. Commented Nov 19, 2010 at 16:29
  • 1
    His answer is correct. Upvoted. You have to return it in the input tag as well
    – Cfreak
    Commented Nov 19, 2010 at 16:32
  • 1
    Also, I'd rather use ev.preventDefault() or ev.returnValue = false to cancel default behavior but not prevent event bubbling, in case other controls observe the same event on the same element. Use return false only when you want to stop the event from bubbling and cancel the default action. See this article. Commented Nov 19, 2010 at 16:34
  • Having to return it in the event handler itself is the very major piece of information that was missing from the answer. Without that, the answer is incomplete and doesn't help enough to be worth an upvote.
    – Quentin
    Commented Nov 19, 2010 at 16:37
0
<input type='button' onclick='buttonClick()' />

<script>
function buttonClick(){
    //Validate Here
    document.getElementsByTagName('form')[0].submit();
}
</script>
1
  • 2
    For a useful answer this reaction needs to be extended. Explain why this is an answer to the question. Commented Aug 14, 2018 at 15:49

Not the answer you're looking for? Browse other questions tagged or ask your own question.