JS Group Events

I currently have four change() events that fire exactly the same code (see below), so I am wondering if there is a way to group these events on the same line in order to save the repeated code four times?

Thanks.

 /** Check for a change to any of the search dropdowns */ $('#job-roles').change(function(e){ letter = $_GET('staff_search'); initiate_staff_search(letter, '<?php echo $staff_search_nonce; ?>', '<?php echo $name_search_type; ?>') }); $('#ind-services').change(function(e){ letter = $_GET('staff_search'); initiate_staff_search(letter, '<?php echo $staff_search_nonce; ?>', '<?php echo $name_search_type; ?>') }); $('#bus-services').change(function(e){ letter = $_GET('staff_search'); initiate_staff_search(letter, '<?php echo $staff_search_nonce; ?>', '<?php echo $name_search_type; ?>') }); $('#indi-services').change(function(e){ letter = $_GET('staff_search'); initiate_staff_search(letter, '<?php echo $staff_search_nonce; ?>', '<?php echo $name_search_type; ?>') }); 
+4
source share
4 answers
 $('#job-roles, #indi-services, #ind-services, #bus-services').change(function(e){ letter = $_GET('staff_search'); initiate_staff_search(letter, '<?php echo $staff_search_nonce; ?>', '<?php echo $name_search_type; ?>') }); 
+5
source

Option 1 : give them all the same classes and attach to them all the events $('.someClass').change(...)

Option 2 Group the event: $('#job-roles, #ind-services, ... ').change(...)

+5
source

Use class?

Give all elements the say doSomething class, and then use the following code to implement the listener:

 $('.doSomething').change(function(e){ letter = $_GET('staff_search'); initiate_staff_search(letter, '<?php echo $staff_search_nonce; ?>', '<?php echo $name_search_type; ?>') }); 
+4
source

Another option, besides the excellent ones already described, is simply:

 (function(){ function doCoolStuff(){ letter = $_GET('staff_search'); initiate_staff_search(letter, '<?php echo $staff_search_nonce; ?>', '<?php echo $name_search_type; ?>') } $('#job-roles').change(function(e){ doCoolStuff(); }); $('#ind-services').change(function(e){ doCoolStuff(); }); $('#bus-services').change(function(e){ doCoolStuff(); }); $('#indi-services').change(function(e){ doCoolStuff(); }); }()); 
+1
source

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


All Articles