2013-02-22 88 views
8

提交按钮,我想阻止提交与onclick事件提交按钮:防止onclick事件从提交

$j('form#userForm .button').click(function(e) { 
    if ($j("#zip_field").val() > 1000){ 
     $j('form#userForm .button').attr('onclick','').unbind('click'); 
     alert('Sorry we leveren alleen inomstreken hijen!'); 
     e.preventDefault(); 
     return false; 
    } 
}); 

这是提交按钮:

<button class="button vm-button-correct" type="submit" 
onclick="javascript:return myValidator(userForm, 'savecartuser');">Opslaan</button> 

它会显示“警报“功能,并且还会删除onclick事件,但表单无论如何都会被提交。在提交之前手动删除onclick事件将解决问题。然而,这是核心功能,我不想删除它。

编辑:

这肯定通过的onclick选择造成的。我怎么能强迫我的jQuery脚本立即重新加载onclick事件?加入jQuery代码之前:$j('form#userForm .button').attr('onclick','');会解决问题。但是我的验证将无法正常工作的了...

+0

你应该真正做到这一点的形式提交处理..如果你按下回车键当表单有焦点..它会触发提交处理程序,而不是你的点击,因此你的验证将被绕过 – 2013-02-22 15:44:15

回答

18

你需要将事件添加作为参数:

$j('form#userForm .button').click(function(event) { // <- goes here ! 
    if (parseInt($j("#zip_field").val(), 10) > 1000){ 
     event.preventDefault(); 
     $j('form#userForm .button').attr('onclick','').unbind('click'); 
     alert('Sorry we leveren alleen inomstreken hijen!'); 
    } 
}); 

而且,val()总是返回一个字符串,所以一个好的做法是在将它与数字进行比较之前将其转换为数字,并且我不确定您是否真的在该函数内部针对#userForm内的所有.button元素,或者如果您应该使用而不是this

如果你使用jQuery 1.7+,你应该考虑使用on()off()

+0

thx,我编辑的代码,但它不工作..我猜onclick事件打破prevent.default ...? – 2013-02-22 15:21:37

+0

内联的onclick将始终首先执行,同时拥有这样的内联函数和事件处理程序并不是一个好习惯,您应该重新考虑这一点,并仅处理事件处理函数,然后调用'myvalidator ()'从外部事件处理程序。 – adeneo 2013-02-22 15:41:44

+1

很多thx!我现在发现了;)但是我不想打破virtmart的核心代码。所以这就是为什么我试图解决这个问题! – 2013-02-22 15:44:48

0

不要忘了,还有功能/事件参数,但必须指定的参数:

$("#thing").click(function(e) { 
    e.preventDefault(); 
}); 

通过这种方式,提交停止,所以你可以conditionalise它。

12

基本上,如果您将按钮类型从type="submit"更改为type="button",则此按钮不会提交表单,也不需要解决方法。

希望这会有所帮助。

+0

很多thx ...但我很肯定onclick事件是责怪 – 2013-02-22 15:31:59

+0

这个答案解决了我的情况,对我来说这应该被标记为正确的答案,因为它更通用:)非常感谢! – 2014-07-03 13:47:56

+0

我正在使用JQuery验证。我有一个'type =“button”'的按钮,但仍然在验证失败时回传表单! [Here](http://stackoverflow.com/questions/29890544/page-still-postbacks-after-jquery-validation-fail/29890940#29890940) 是我的问题。 – sohaiby 2015-04-27 08:58:37

0

最好的方法是在你的提交事件处理程序的表单中做所有事情。的onclick删除内联并运行它提交函数内部

$j('#userForm').submit(function(e) { 
    if (+$j("#zip_field").val() > 1000){ 
     alert('Sorry we leveren alleen inomstreken hijen!'); 
     return false; 
    } 
    return myValidator(userForm, 'savecartuser'); 
}); 
-2

我相信有一个简单的方法:

$j('form#userForm .button').click(function(event) { // <- goes here ! 
    if (parseInt($j("#zip_field").val(), 10) > 1000){ 
     event.stopPropagation(); 
    } 
});