如何拦截提交按钮的点击? [英] How to intercept a submit button click?

查看:32
本文介绍了如何拦截提交按钮的点击?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单和一个提交按钮.

I have a form and a submit button.

我想快速检查一些字段(如果没有填写,则将其他一些空白).

I want to do a quick check on some of the fields (if one isn't filled in, then to blank some of the others).

我不想更改按钮的 HTML,我只想在 jQuery 中执行此操作,而不向按钮添加任何onclick"属性.

I would rather not change the HTML for the button, I would like to just to do this in jQuery and not add any "onclick" attributes to the button.

HTML:

<input class="cssButton button_in_cart" type="submit" value="Add to Bag" style="width: 80px;">

jQuery(尝试):

jQuery (attempted):

$("input.button_in_cart").mousedown(function () {
    alert("clicked");   
});

这不起作用,它仍然提交表单而不显示警报.谢谢.

This doesn't work, it still submits the form without showing the alert. Thanks.

推荐答案

不要使用任何形式的单击事件进行表单处理,因为键盘提交会绕过您的代码!

Do not use any form of click event for form processing as keyboard submission will bypass your code!

改用 submit 事件处理程序并返回 false(或 e.preventDefault())以停止提交过程.

Use the submit event handler instead and return false (or e.preventDefault()) to stop the submit proceeding.

例如

$('#myform').submit(function(e){
   // Do your validation here
   // ...
   // Then conditionally stop the submit from firing
   if (someValidateFails){
      e.preventDefault()
   }
});

这篇关于如何拦截提交按钮的点击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆