Can I use jquery for onKeyUp for multiple elements?

I have a bunch of text fields in which I want to run a function when doing onkeyup. They will run the same function, so there is a way that I can just do this on one line instead:

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

Also, if I can do this, how can I drop and swap there for the drop-down list? Thanks everyone!

+4
source share
3 answers

You can use commas to separate items:

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

But what about using classes instead of listing all identifiers:

 <!-- HTML --> <input id="element1" class="element" /> <input id="element2" class="element" /> // JavaScript $(".element").keyup(getData); 
+9
source

Or you add them to your selector:

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

or you use add() , which in this case is likely to be more efficient, since jQuery can use the ID-only selector shortcut using getElementById :

 $('#element1').add('#element2').keyup(function(){ // ... 
+2
source

It is possible to use multiple selectors within $() .

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

or shorter

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

If you want to associate the .change() event with multiple select fields, then give all select common class

 <select class="myselect"></select> <select class="myselect"></select> <select class="myselect"></select> $('.myselect').on('change', function() { }); 
+1
source

Source: https://habr.com/ru/post/1415223/


All Articles