Tintin81
Tintin81

Reputation: 10215

How to combine two event handlers into one in 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.

Upvotes: 6

Views: 8236

Answers (2)

Jorge Silva
Jorge Silva

Reputation: 4604

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();
  }
});

Upvotes: 10

Slippery Pete
Slippery Pete

Reputation: 3110

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);

Upvotes: 6

Related Questions