Jordan Carter Jordan Carter - 6 months ago 12
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) {
event.preventDefault();
}

Answer

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) {
      event.preventDefault();
    }
    

    Then assign the event handler like that:

    $(btnSubmit).click(validate);
    
  2. Use an anonymous function that will pass the btnSubmit and event to validate:

    $(btnSubmit).click(function(event) {
      validate(btnSubmit, event)
    });
    
Comments