LB.
LB.

Reputation: 14112

How to intercept the onclick event

I'd like to intercept the onclick event of a button (not submit) before the page posts back from the onclick.

I'm having some trouble:

$(document).ready() { function() {
    function validate() { 
        ...
    }

    var oldOnClick = $("input[value=OK]").attr("onclick");
    $("input[value=OK]").attr("onclick", "if(!validate()) { return false; }" + oldOnClick));
});

Upvotes: 7

Views: 14913

Answers (4)

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827256

If you still want to handle the button click event instead of the form submit event as all suggested, you could do something like this, using an anonymous function, to call your oldOnClick function, preserving the context and the event 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
  });
});

Upvotes: 9

Sean Vieira
Sean Vieira

Reputation: 159885

e.preventDefault();

More specifically you need to do this

$("#Your_form_id").submit(function(e) {
e.preventDefault();
// your code
});

The other way to do this, is as Jake says, return false after doing some work ... ie:

$("#Your_form_id").submit(function() {
// your code
return false;
});

See the Jquery documentation on Submit and Events in general

Upvotes: 0

jakeisonline
jakeisonline

Reputation: 1206

Rather than trying to intercept the onClick event, you should use the submit event.

Why? Simple, not all forms are submitted by clicking, what about tab, enter, etc?

$("form").submit(function() { // do validation/stuff here }); will do the trick.

You can return false; to stop the form submitting, or return true; if you want to let it through. Do your validation within the .submit itself.

Upvotes: 4

wtaniguchi
wtaniguchi

Reputation: 1324

OnSubmit is called just before the form is submit. You can even cancel the event, so the form isn't submitted.

Upvotes: 0

Related Questions