Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine two event handlers into one in jQuery?

Tags:

jquery

Is there a simple way to combine these two jQuery functions into one, thereby removing the 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.

like image 734
Tintin81 Avatar asked Aug 25 '14 20:08

Tintin81


2 Answers

If you want to bind these conditionally in the most elegant, shortest way possible 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 event to be triggered for both selectors, you can do this. It might be okay to do this, since you might want these to be triggered anyways.

$('form#search input, form#search select').on('keyup change', function() {
    if ($(this).val() == '') {
    $('a#clear').hide();
  }
  else {
    $('a#clear').show();
  }
});
like image 171
Jorge Silva Avatar answered Sep 29 '22 09:09

Jorge Silva


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);
like image 28
Slippery Pete Avatar answered Sep 29 '22 07:09

Slippery Pete