user5013
user5013

Reputation: 1001

Using the each function to pass results to another function

I guess this might be a noob question but when using the each iterator, is it possible to send the results to a predefined function? I have only seen examples where the function is defined in the parantheses. Here is what I would like to do:

function setCheckboxes(key, value) {
    ....some code....
}

context.find('input[type="checkbox"]').each(setCheckboxes(key, value));

Is this possible? Or do I have to implement it this way:

context.find('input[type="checkbox"]').each(function(key, value) {
    ....some code....
});

Upvotes: 0

Views: 54

Answers (2)

PSL
PSL

Reputation: 123739

You can just give the function reference as the callback for each.

context.find('input[type="checkbox"]').each(setCheckboxes);

In your callback setCheckboxes key will be the index and value will be the element (DOM element).

This is no different from writing an anonymous function, where you get the same 2 arguments, in this case you are just giving a reference to a function that expects the same 2 arguments. So the context inside the callback i.e setCheckboxes will be the DOM element.

Upvotes: 4

sbeliv01
sbeliv01

Reputation: 11820

You should be able to do:

function setCheckboxes(key, value) {
    ....some code....
}

context.find('input[type="checkbox"]').each(function(key, value){
    setCheckboxes(key, value);
});

Upvotes: 0

Related Questions