Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Selector - Multiple Items

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.

like image 518
maxp Avatar asked Aug 01 '11 10:08

maxp


Video Answer


1 Answers

.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.

like image 193
jensgram Avatar answered Nov 09 '22 10:11

jensgram