Jordan Carter Jordan Carter - 1 year ago 146
Javascript Question

JavaScript event.preventDefault() with other arguements

I have this call to a function, which I want to pass the parameter btnSubmit:

$(btnSubmit).click( validate(btnSubmit, event) );

I want to first prevent the form from submitting and then validate. However, it submits anyway. It works if I don't pass btnSubmit in, but I would like to do that.

function validate (btnSubmit, event) {

Answer Source

When you're doing:

$(btnSubmit).click( validate(btnSubmit, event) );

you're immediately calling the validate function and you're passing its returned value as a callback for $(btnSubmit).click(). Since that function doesn't return anything, no event handler is actually created.

You have two possible solutations:

  1. As squint suggested, change the validate function to use this instead of btnSubmit and have event as the first argument:

    function validate (event) {

    Then assign the event handler like that:

  2. Use an anonymous function that will pass the btnSubmit and event to validate:

    $(btnSubmit).click(function(event) {
      validate(btnSubmit, event)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download