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.
You can do this:
The
.each()call creates a closure, inside itthisrefers 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 usethisinsidefoo(instead of the DOM element as a parameter) you can shorten it down to:Here’s a demonstration of that method
Also, make sure you’re running this on
document.readylike this:Otherwise the DOM elements may not be there to find, making that selector return an empty array (so nothing to run on).