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

      

+2


source to share


4 answers


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

      

+7


source


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

.

+3


source


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

0


source


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

      

See jQuery documentation on Submit and Events in general

0


source







All Articles