How do I cancel form submission in submit button o

2019-01-02 17:53发布

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?

12条回答
梦该遗忘
2楼-- · 2019-01-02 18:28

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

查看更多
刘海飞了
3楼-- · 2019-01-02 18:33

It's simple, just return false;

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

if(conditionsNotmet)
{
return false;
}
查看更多
后来的你喜欢了谁
4楼-- · 2019-01-02 18:34

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();
} 
查看更多
ら面具成の殇う
5楼-- · 2019-01-02 18:35

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;
}
查看更多
皆成旧梦
6楼-- · 2019-01-02 18:38

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");
            });
 });
查看更多
初与友歌
7楼-- · 2019-01-02 18:38
function btnClick() {
    return validData();
}
查看更多
登录 后发表回答