How to combine two event handlers in one of jQuery?

Is there an easy way to combine these two jQuery functions into one, thereby eliminating unnecessary duplication?

$('form#search input').on('keyup', function() { if ($(this).val() == '') { $('a#clear').hide(); } else { $('a#clear').show(); } }); $('form#search select').on('change', function() { if ($(this).val() == '') { $('a#clear').hide(); } else { $('a#clear').show(); } }); 

Thanks for any help.

+5
source share
2 answers

If you want to link these conditionally in the most elegant, shortest way, you can do this:

 var $formSearch = $('form#search'), hideShow = function () { if ($(this).val() == '') { $('a#clear').hide(); } else { $('a#clear').show(); } }; $formSearch.find('input').on('keyup', hideShow); $formSearch.find('select').on('change', hideShow); 

If you want both events to fire for both selectors, you can do this. Perhaps this will be normal, as you may want them to be running anyway.

 $('form#search input, form#search select').on('keyup change', function() { if ($(this).val() == '') { $('a#clear').hide(); } else { $('a#clear').show(); } }); 
+9
source

Define one function to handle the event, and then assign it as follows:

 function inputChanged() { if ($(this).val() == '') { $('a#clear').hide(); } else { $('a#clear').show(); } } $('form#search input').on('keyup', inputChanged); $('form#search select').on('change', inputChanged); 
+6
source

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


All Articles