阻止带有onclick事件的提交按钮提交 [英] Prevent submit button with onclick event from submitting
问题描述
我想阻止带有onclick事件的提交按钮提交:
I want to prevent a submit button with onclick event from submitting:
$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事件将解决问题.但这是的核心功能,我不想删除它.
It will show the "alert" function and also removes the onclick event, but the form is submitted anyway. Manually remove the onclick event before submitting will solve the problem. However this is core functionality of and I dont want to remove it.
这肯定是由onclick选择器引起的.如何强制我的jQuery脚本立即重新加载onclick事件?在jquery代码之前添加:$j('form#userForm .button').attr('onclick','');
将解决问题..但是我的验证不再起作用...
It's definitely caused by the onclick selector.. How can I force my jQuery script to instantly reload the onclick event? adding before jquery code: $j('form#userForm .button').attr('onclick','');
will solve issue.. however my validation won't work an anymore...
推荐答案
您需要将事件添加为参数:
You'll need to add the event as a parameter:
$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
元素作为目标在函数内的#userForm
里面,还是应该使用this
呢?
Also, val()
always returns a string, so a good practice would be to convert it to a number before you compare it to a number, and I'm not sure if you're really targeting all .button
elements inside #userForm
inside the function, or if you should use this
instead?
如果您使用的是jQuery 1.7+,则应该考虑使用on()
和off()
.
If you're using jQuery 1.7+, you should really consider using on()
and off()
for this.
这篇关于阻止带有onclick事件的提交按钮提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!