Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind a function on multiple jQuery elements at once

I have 3 jquery objects:

var a = $('.el1');
var b = $('.el2');
var c = $('.el3');

And I want to bind a "change" event to all of them at once, but I can't :(

$(a, b, c).bind('paste input change', function(){ ... }); simply doesn't work...

But if bind it to each element separately it works:

a.bind('...');
b.bind('...');
c.bind('...');

Is it possible to do this in a shorter way?

(And without passing the classes as selectors)

like image 572
Alex Avatar asked Nov 06 '11 00:11

Alex


2 Answers

Use .add() [docs]:

a.add(b).add(c).bind(...
like image 99
Felix Kling Avatar answered Sep 21 '22 07:09

Felix Kling


$([a,b,c]).bind should work, as in:

var a = $('.el1');
var b = $('.el2');
var c = $('.el3');

$([a,b,c]).each(function(idx){
    $(this).bind('click', function(){
       alert($(this).text());
    });
});
like image 43
GreyBeardedGeek Avatar answered Sep 21 '22 07:09

GreyBeardedGeek