Skullomania
Skullomania

Reputation: 2215

How do I ignore null or all spaces in my filter?

I have created a jQuery filter that gets a department's name from a list of divs. Currently, if someone enters a bunch of spaces into the field no departments will display. Is it possible, however, to display everything if only spaces are entered?

Here is what my filter looks like:

$("#filter").keyup(function(){
var selectDept = $(this).val().toLowerCase();
filter(selectDept);
});

function filter(e) {
var regex = new RegExp('\\b\\w*' + e + '\\w*\\b');
        $('.dept').hide().filter(function () {
    return regex.test($(this).data('department'))
    }).show();
}

Upvotes: 1

Views: 529

Answers (1)

charlietfl
charlietfl

Reputation: 171679

Use trim() on your value to remove whitespace from each end and don't call filter() if it has no length(is falsy) and show all the .dept class instead

$("#filter").keyup(function() {
  var selectDept = $(this).val().trim().toLowerCase();
  if (selectDept) {// empty string is falsy
    filter(selectDept);
  } else {
    $('.dept').show()
  }
});

Upvotes: 1

Related Questions