tags:

views:

993

answers:

4

I have 4 jQuery objects (i.e. things constructed via $("ObjectID")), and I would like to perform the same operation to all of them, in an elegant fashion. I would have thought that something like these would work, but it doesn't seem to:

$([obj1, obj2, obj3, obj4]).change(function() { otherObj.show(); });
$([obj1, obj2, obj3, obj4]).attr("disabled", "disabled");

Is there a good syntax for this? It seems like a somewhat blinding oversight. Currently the best I'm seeing is

$([obj1, obj2, obj3, obj4]).each(
    function() { this.change(function() { otherObj.show(); }));
+2  A: 

Try attaching a class to the objects when you create them and doing

$(".class")
    .change(function(){otherObj.show();})
    .attr("disabled","disabled");
Rob Stevenson-Leggett
This is probably the best solution, but the answer I accepted is the one that will work in all circumstances.
Domenic
+2  A: 

You mean you have:

var obj1 = $("...");
var obj2 = $("...");
var obj3 = $("...");
var obj4 = $("...");

?

If so, you can turn them into a single set:

var complete = obj1.add(obj2).add(obj3).add(obj4);

and then just use the final set to:

complete.change(function() {
  otherObj.show();
}).attr("disabled", true);
cletus
That's it! A bit annoying, but all good.
Domenic
According to http://docs.jquery.com/Traversing/add the .add() function isn't limited to one new element at a time
Gareth
+2  A: 

This will work for ids:

$("#obj1,#obj2,#obj3,#obj4")

It will also work for any selector. You can combine anything in a comma separated list.

kgiannakakis
A: 

Using the each command is certainly one way of tackling it, however there are other approaches.

You can peel away the jQuery object to get an array, perform whatever you need to do on the array and then wrap it back into a jQuery object.

There are also a number of plugins with array methods and enumurables that allow you to manipulate arrays and jQuery objects.

Russ Cam