通过更改事件防止两次提交表单 [英] Prevent submit form twice with change event

查看:77
本文介绍了通过更改事件防止两次提交表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有隐藏的提交按钮和一个文本输入的表单.在文本输入中,我将jQuery附加到它的change事件中,该事件提交了表单.关键是,如果我在输入中按回车键,则表单将提交两次.我认为是因为Enter提交表单,而输入检测到更改事件,然后再次提交表单.我有两个问题:-我的想法对吗?-我该如何解决?

i hava a form with a hidden submit button and one text input. In the text input, with jQuery i attached to it a change event that submits the form. The thing is that if i hit enter on the input, then the form submits twice. I think is because the enter submits the form and the input detects a change event and it submit the form again. I have two questions: - Is my thought right? - How can i fix this?

这是javascript:

This is the javascript:

$("input.price").live('change', function () {
  $(this).closest('form').submit();
});

我认为e.preventDefault()阻止了事件更改"的默认设置,但没有阻止事件提交".解决方案:

I think that the e.preventDefault() is preventing the default of the event "change" but no preventing the event "submit".. i try this before the event "change" with no luck but maybe im close to the solution:

$("input.price").live('submit', function (e) {
       e.preventDefault();
});

推荐答案

最后,我提出了解决方案!事实是……正如Mike C.所说,额外的代码可以帮助解决问题.问题是我要提交的表单是MVC的Ajax.BeginForm,所以..主要问题是该表单的ajax提交,这是第二个提交!

Finally i came out with a solution! The thing was that.. as Mike C. says, the extra code could help to solve the problem. The problem was that the form that i'm trying to submit it's an Ajax.BeginForm of MVC so.. the main problem is the ajax submit of that form, that was the second submit!

我无法更改该行为..仅更改带有Html.Beginform ..的Ajax.Beginform ..我不想做的事情.所以..我想到了这个生锈"的解决方案:

I couldn't change that behavior.. only changing the Ajax.Beginform with a Html.Beginform.. thing that i don't want to do. So.. i came out with this "rusty" solution:

$("input.price").live('keypress', function (e) {
     if (e.keyCode == 13) {
        $(this).attr('data-submitting', true);
     }
});

$("input.price").live('change', function (e) {
     if (!$(this).attr('data-submitting')) {
         $(this).closest('form').submit();
     }
});

这篇关于通过更改事件防止两次提交表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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