通过提交的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; } }); 

这是提交按钮:

  

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

编辑:

它肯定是由onclick选择器引起的。如何强制我的jQuery脚本立即重新加载onclick事件? 在jquery代码之前添加: $j('form#userForm .button').attr('onclick',''); 将解决问题..但是我的validation将不再适用…

您需要将事件添加为参数:

 $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()总是返回一个字符串,所以一个好的做法是将它转换为数字,然后再将它与数字进行比较,我不确定你是否真的瞄准.button里面的所有.button元素function,或者你应该使用this吗?

如果您使用的是jQuery 1.7+,那么您应该考虑使用on()off()

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

希望这可以帮助。

不要忘记有函数/事件参数,但必须指定参数:

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

这样,提交就会停止,因此您可以对其进行条件化。

最好的方法是在表单的提交事件处理程序中执行所有操作。 删除内联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'); }); 

我相信有一种更简单的方法:

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