Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
864 views
in Technique[技术] by (71.8m points)

jquery - Prevent submit button with onclick event from submitting

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

This is the submit button:

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

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.

EDIT:

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...