111

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?

Vivian River
  • 31,198
  • 62
  • 198
  • 313
  • 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. – Vivian River Nov 19 '10 at 16:39
  • 2
    possible duplicate of [How to prevent form from being submitted?](http://stackoverflow.com/questions/3350247/how-to-prevent-form-from-being-submitted) – T J Sep 29 '14 at 19:26

14 Answers14

205

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();
};
Saminda Peramuna
  • 735
  • 9
  • 22
alex
  • 479,566
  • 201
  • 878
  • 984
  • 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... – Vivian River Nov 19 '10 at 16:30
  • 8
    You can use his second suggestion. Inline javascript is the devil anyway. – Stephen Nov 19 '10 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 Nov 19 '10 at 16:32
  • @David, if using other forms is incompatible with ASP.net web forms, then should I only use server-side controls? – Vivian River Nov 19 '10 at 16:34
  • 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 Nov 19 '10 at 16:35
  • Is it compatible with IE8? – Flash Thunder Mar 11 '14 at 21:23
  • @FlashThunder It's compatible with Netscape 1.9 probably ;) – alex Mar 11 '14 at 22:18
  • 2
    Someone else have answered EXACTLY like you http://stackoverflow.com/a/23604664/1639385. I think it was too much a coincidence. – Ulysses Alves Nov 10 '15 at 11:54
47

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;
}
mikefrey
  • 4,653
  • 3
  • 29
  • 40
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).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
7

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");
            });
 });
Shady Mohamed Sherif
  • 15,003
  • 4
  • 45
  • 54
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.

devrys
  • 1,571
  • 3
  • 27
  • 43
Mohammed
  • 61
  • 1
  • 1
5

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.

Kira-Bianca
  • 59
  • 1
  • 2
4

You need to return false;:

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

function btnClick() {
    return validData();
}
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
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>
Tidoy007
  • 79
  • 7
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();
} 
George Johnston
  • 31,652
  • 27
  • 127
  • 172
1

It's simple, just return false;

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

if(conditionsNotmet)
{
return false;
}
omar-ali
  • 507
  • 4
  • 14
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.

Cfreak
  • 19,191
  • 6
  • 49
  • 60
  • this won't work. if data is valid you do not return true. put return true; at the end of btnClick() function – NickSoft Nov 08 '13 at 07:21
0

use onclick='return btnClick();'

and

function btnClick() {
    return validData();
}
Adam
  • 619
  • 1
  • 4
  • 19
0
function btnClick() {
    return validData();
}
mbeckish
  • 10,485
  • 5
  • 30
  • 55
  • 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. – Vivian River Nov 19 '10 at 16:29
  • 1
    His answer is correct. Upvoted. You have to return it in the input tag as well – Cfreak Nov 19 '10 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](http://javascript.about.com/library/bldom21.htm). – Klemen Slavič Nov 19 '10 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 Nov 19 '10 at 16:37
0
<input type='button' onclick='buttonClick()' />

<script>
function buttonClick(){
    //Validate Here
    document.getElementsByTagName('form')[0].submit();
}
</script>
ggorlen
  • 44,755
  • 7
  • 76
  • 106
Person
  • 1