Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i use jquery for onKeyUp on multiple elements?

Tags:

jquery

i have a bunch of text fields that i want to run a function when onkeyup is done. They will all run the same function so is there a way i can just do that on one line instead of this:

$('#element1').keyup(function(){getData()});
$('#element2').keyup(function(){getData()});

Also, if i can do that, how can i throw and onchange in there for a dropdown? Thanks all!!

like image 286
Damien Avatar asked May 30 '12 18:05

Damien


3 Answers

You can use commas to separate elements:

$("#element1, #element2").keyup(getData);

But how about using classes instead of listing all IDs:

<!-- HTML -->
<input id="element1" class="element" />
<input id="element2" class="element" />

// JavaScript
$(".element").keyup(getData);
like image 183
VisioN Avatar answered Nov 01 '22 09:11

VisioN


Either you append them in your selector:

$('#element1, #element2').keyup(function(){ // ...

or you use add() which in this case will probably be more efficient, as jQuery can use a shortcut for ID-only selectors using getElementById:

$('#element1').add('#element2').keyup(function(){ // ...
like image 30
Mattias Buelens Avatar answered Nov 01 '22 09:11

Mattias Buelens


Its possible to use multiple selectors within $().

$('#element1, #element2').keyup(function(){
   getData()
 });

or in short

$('#element1, #element2').keyup(getData);

If you want to bind .change() event to you multiple select box then give all select a common class

<select class="myselect"></select>
<select class="myselect"></select>
<select class="myselect"></select>

$('.myselect').on('change', function() {

});
like image 21
thecodeparadox Avatar answered Nov 01 '22 10:11

thecodeparadox