JasonF JasonF - 2 months ago 7
jQuery Question

How do I get jQuery to recognise separate values

I have a got some jQuery working to make a simple search / filter feature. The feature allows a user to type in the text field and it in turn shows only the list items which have those characters i.e. type 'red' it shows all list items with 'red' in it.

My problem is that it only works for the exact input i.e. if type in 'red blue', it will only find 'red blue', not 'blue red'or other 'red' items.

Could anyone help in a solution to my problem?

Here's my code:



$('#box').keyup(function() {
var valThis = $(this).val().toLowerCase();
if (valThis == "") {
$('.filterlist>li').show();
} else {
$('.filterlist>li').each(function() {
var text = $(this).text().toLowerCase();
(text.indexOf(valThis) >= 0) ? $(this).show(): $(this).hide();
});
};
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="box" type="text" placeholder="Search">

<ul class="filterlist" style="list-style:none;">
<li>red</li>
<li>blue</li>
<li>red blue</li>
<li>blue red</li>
</ul>




Answer
$('#box').keyup(function() {
  var valThis = $(this).val().toLowerCase();

  if (valThis == "") {
    $('.filterlist>li').show();
  } else {
    var subValues = valThis.trim().split(' ');

    $('.filterlist>li').each(function () {
      var node = $(this);
      var text = node.text().toLowerCase();

      if (subValues.some(function (word) {
        return text.indexOf(word) !== -1;
      })) {
        node.show();
      }
      else {
        node.hide();
      }
    });
  };
});

https://jsfiddle.net/0xjwapdf/

As suggested in the comments, we split the search terms into separate words, and then search for each of those words.