0

Say I have these variables:

var container = $("div#my-awesome-section"); var foo_input = $("input[name=foo]", container); var bar_input = $("input[name=bar]", container); 

I want to bind an event handler to both inputs. I hoped this would work:

$([foo_input, bar_input]).on("keypress", function() { /* ... */ }); 

But alas, no. Is there a convenient way of gathering multiple jQuery objects into one for purposes like this?

4 Answers 4

4

use in add() in jquery for adding jquery object

foo_input.add(bar_input).on("keypress", function() { /* ... */ }); 
Sign up to request clarification or add additional context in comments.

Comments

1

Solution 1:

for using with object, you need to use .add()

Create a new jQuery object with elements added to the set of matched elements.

 foo_input.add(bar_input).on("keypress", function() { /* ... */ }); 

Solution 2:

also you can simply use comma separated multiple selector:

 $("input[name=foo],input[name=bar]", container).on("keypress", function() { /* ... */ }); 

2 Comments

I have bound the jQuery objects to variables so I won't have to repeat the selectors elsewhere. Having to repeat the selectors every time I bind an event handler would defeat that purpose.
you are looking for .add(). see the first part.
0

You can also try this:

$.each([foo_input, bar_input], function() { /* ... */ }); 

See JSFiddle.

In your case use:

$.each([foo_input, bar_input], function() { $(this).on("keypress", function() { /* ... */ }); }); 

Comments

0

Reading the docs for jQuery's add() function, I noticed that my original attempt was almost correct. It is possible to initialize a jQuery object with an array of DOM Elements, so I could do this:

$([foo_input[0], bar_input[0]]).on("keypress", ... 

I highly prefer the add() function though.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.