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.
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();
}
});
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With