Prevent submit button with onclick event from submitting

后端 未结 5 1670
一向
一向 2020-12-17 10:21

I want to prevent a submit button with onclick event from submitting:

$j(\'form#userForm .button\').click(function(e) {
    if ($j(\"#zip_field\").val() >         


        
5条回答
  •  醉话见心
    2020-12-17 10:57

    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.

提交回复
热议问题