Prevent submit button with onclick event from submitting

末鹿安然 提交于 2019-11-29 06:11:01

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!');
    }   
});

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?

If you're using jQuery 1.7+, you should really consider using on() and off() for this.

Basically, if you change your button type from type="submit" to type="button", such button won't submit form, and no workarounds are needed.

Hope this helps.

Don't forget that there are function/event arguments, but you must specify the parameters:

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

In this way, the submission is halted, and so you can conditionalise it.

Best way is to do everything inside your submit event handler of the form. Remove the inline onclick and run it inside the submit function

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

I believe there is an easier way:

$j('form#userForm .button').click(function(event) { // <- goes here !
    if ( parseInt($j("#zip_field").val(), 10) > 1000){
        event.stopPropagation();
    }   
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!