Reputation: 25141
Say I have two jquery selections:
var txtA = $('#txtA');
var txtB = $('#txtB');
In order to attach the same event function, is this the neatest way, or am I missing an obvious piece of syntax or jquery wizardness?
$(jQuery.merge(txtA , txtB )).click(function () { alert('hello'); });
Thanks.
Upvotes: 7
Views: 3693
Reputation: 472
Here is what I have done:
$()
.add(elementOne)
.add(elementTwo)
.add(elementThree)
.click(function() {
alert('hello');
});
Upvotes: 1
Reputation: 17091
You can just do:
$("#txtA, #txtB").click(function () { alert('hello'); });
The same as a CSS selector, cool huh! :-)
Upvotes: 0
Reputation: 31508
.add()
should do (provided that you have already populated txtA
and txtB
and want the reuse those selections.):
txtA.add(txtB).click(function () {
alert('hello');
});
Given a jQuery object that represents a set of DOM elements, the
.add()
method constructs a new jQuery object from the union of those elements and the ones passed into the method. The argument to.add()
can be pretty much anything that$()
accepts, including a jQuery selector expression, references to DOM elements, or an HTML snippet.
Upvotes: 9
Reputation: 176896
$('#txtA, #txtB').click(function () { alert('hello'); });
may work for you
Upvotes: 2