maxp
maxp

Reputation: 25141

Using Jquery, call function on selection just once

Say i have a selection of textboxes like this;

var arrayoftextboxes = $('.textbox1, .textbox2, .textbox3');

Is there a way I can call a function on each one in a simpler way than this? It only needs to be called once.

arrayoftextboxes.each(function(i){foo(arrayoftextboxes[i]);});

I tried

arrayoftextboxes.load(function(){foo(this)});

and

arrayoftextboxes.bind(function(){foo(this)});

but the functions dont seem to be called.

Upvotes: 0

Views: 1812

Answers (1)

Nick Craver
Nick Craver

Reputation: 630429

You can do this:

$('.textbox1, .textbox2, .textbox3').each(function() { foo(this); });

The .each() call creates a closure, inside it this refers to the DOM element you're currently on, but it may be better to write what you have as a jQuery plugin. Or, if you just use this inside foo (instead of the DOM element as a parameter) you can shorten it down to:

$('.textbox1, .textbox2, .textbox3').each(foo);

Here's a demonstration of that method

Also, make sure you're running this on document.ready like this:

$(function() {
  $('.textbox1, .textbox2, .textbox3').each(foo);
});

Otherwise the DOM elements may not be there to find, making that selector return an empty array (so nothing to run on).

Upvotes: 3

Related Questions