Makis
Makis

Reputation: 1244

jQuery - JavaScript, pass a parameter to a function alongside with "event"

I want to achieve to pass a parameter to a function with an event handler.

What i'm trying to achieve is something like this

$('#Form').submit(save(parameter));

function save(event, parameter){
   event.preventDefault();
}

In which way should i make it?

Upvotes: 0

Views: 94

Answers (2)

Andreas
Andreas

Reputation: 2075

There are two ways to achieve this. The first one is a closure:

$('#Form').submit( function (event) { save(event, parameter); });

The second one is the bind-function:

$('#Form').submit(save.bind(null, parameter));

function save(parameter, event){
   event.preventDefault();
}

Please note that you need to reorder the parameters of "save" here. The first parameter of the bind-function is the value for "this" inside the save-function. Here it is "null" which means "unchanged".

Upvotes: 1

epascarello
epascarello

Reputation: 207501

That be a job for a closure

$('#Form').submit( function (event) { save(event, parameter); });

Upvotes: 2

Related Questions