How to intercept onclick event
I would like to intercept the onclick event of a button (not dispatch) before the page is posted back from onclick.
I have a problem's:
$(document).ready() { function() {
function validate() {
...
}
var oldOnClick = $("input[value=OK]").attr("onclick");
$("input[value=OK]").attr("onclick", "if(!validate()) { return false; }" + oldOnClick));
});
source to share
If you still want to handle the button click event instead of the form submit event like all suggested, you can do something like this using an anonymous function to call the oldOnClick function, keeping the event context and argument:
$(document).ready(function () {
function validate() {
// ...
}
var oldOnClick = $("input[value=OK]").get(0).onclick;
$("input[value=OK]").click(function (e) {
if(!validate()) {
return false;
}
oldOnClick.call(this, e); // enforce the context and event argument
});
});
source to share
Instead of intercepting the onClick event, you should use dispatch event .
Why? Simple, not all forms are submitted on click, how about tabs, typing, etc.
$("form").submit(function() { // do validation/stuff here });
will do the trick.
You can return false;
stop submitting the form, or return true;
if you want to skip it. Do your check inside yourself .submit
.
source to share
e.preventDefault();
Specifically you need to do this
$("#Your_form_id").submit(function(e) {
e.preventDefault();
// your code
});
Another way to do it, as Jake says, is to return false after doing some work ... ie:
$("#Your_form_id").submit(function() {
// your code
return false;
});
source to share