Attaching an event to multiple elements at one go

JavascriptJqueryEvents

Javascript Problem Overview


Say I have the following :

var a = $("#a");
var b = $("#b");

//I want to do something as such as the following : 

$(a,b).click(function () {/* */}); // <= does not work

//instead of attaching the handler to each one separately

Obviously the above does not work because in the $ function, the second argument is the context, not another element.

So how can I attach the event to both the elements at one go ?


[Update]

peirix posted an interesting snippet in which he combines elements with the & sign; But something I noticed this :

$(a & b).click(function () { /* */ }); // <= works (event is attached to both)

$(a & b).attr("disabled", true); // <= doesn't work (nothing happens)

From what you can see above, apparently, the combination with the & sign works only when attaching events...?

Javascript Solutions


Solution 1 - Javascript

The jQuery add method is what you want:

> Adds more elements, matched by the given expression, to the set of matched elements

var a = $("#a");
var b = $("#b");
var combined = a.add(b)

Solution 2 - Javascript

Don't forget either that jQuery selectors support the CSS comma syntax. If you need to combine two arbitrary collections, everyone else's suggestions are on the mark, but if it's as simple as doing something to elements with IDs a and b, use $('#a,#b').

Solution 3 - Javascript

This question has already been answered, but I think a simpler more streamlined way to accomplish the same end would be to rely on the similarities between jQuery's and CSS's selector model and just do:

$("#a, #b").click(function () {/* */});

I use this frequently, and have never seen it not work (I can't speak for jQuery versions before 1.3.2 though as I have not tested this there). Hopefully this helps someone someday.


UPDATE: I just reread the thread, and missed the comment you made about having the nodes in question already saved off to variables, but this approach will still work, with one minor tweek. you will want to do:

var a = $("#a");
var b = $("#b");
$(a.selector+", "+b.selector).click(function () {/* */});

One of the cool things that jquery does is that it adds a few jquery specific properties to the node that it returns (selector, which is the original selector used to grab that node is one of them). You may run into some issues with this if the selector you used already contained commas. Its also probably arguable if this is any easier then just using add, but its a fun example of how cool jquery can be :).

Solution 4 - Javascript

You could just put them in an array:

$.each([a, b], function()
{
    this.click(function () { });
});

Solution 5 - Javascript

Why don't you use an array? This works on my side:

$([item1, item2]).on('click', function() {
      // your logic
});

Solution 6 - Javascript

I just tried messing around with this, and found something very cool:

$(a & b).click(function() { /* WORKS! */ });

supersweet!

Edit: Now I feel really embarrassed for not testing this properly. What this did, was actually to put the click event on everything... Not sure why it does that, though...

Solution 7 - Javascript

You can also make up a class name and give each element that you want to work with that class. Then you can bind the event to all elements sharing that class.

<p><a class="fakeClass" href="#">Click Me!</a></p>

<p><a class="fakeClass" href="#">No, Click Me!</a></p>

<div class="fakeClass">Please, Click Me!</div>

<script type="text/javascript">
    $(function () {
        $(".fakeClass").on("click", function () {
            alert("Clicked!");
        });
    })
</script>

Solution 8 - Javascript

try this: sweet and simple.

var handler = function() {
    alert('hi!');
}
$.each([a,b], function() {
    this.click(handler);
}

BTW, this method is not worth the trouble.

If you already know there are just two of these methods, then I guess the best bet would be

a.click(handler);
b.click(handler);

Cheers!

Solution 9 - Javascript

Example:

$("[name=ONE_FIELD_NAME], [name=ANOTHER_FIELD_NAME]").keypress(function(e){alert(e.which);});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndreas GrechView Question on Stackoverflow
Solution 1 - JavascriptGarethView Answer on Stackoverflow
Solution 2 - JavascripthobbsView Answer on Stackoverflow
Solution 3 - JavascriptThe Brawny ManView Answer on Stackoverflow
Solution 4 - JavascriptGregView Answer on Stackoverflow
Solution 5 - JavascriptAndrey BoriskoView Answer on Stackoverflow
Solution 6 - JavascriptpeirixView Answer on Stackoverflow
Solution 7 - JavascriptcamaincView Answer on Stackoverflow
Solution 8 - JavascriptjrharshathView Answer on Stackoverflow
Solution 9 - JavascriptDebasish RakshitView Answer on Stackoverflow