lostInTheTetons
lostInTheTetons

Reputation: 1222

Case Insensitive List Filtering

I'm trying to filter a list without worrying about whether a word is capitalized or not.

I have the following HTML:

<ul class="dropdown-menu gatherDropDown" id="list">
   <h3 id="header">Filter by </h3>
   <input id="filter" type="text" name="fname" onkeyup="filterList(this)">
   <li><input type="checkbox" class="item_name"> Producer 1</li>
   <li><input type="checkbox" class="item_name"> Producer 2</li>
   <li><input type="checkbox" class="item_name"> Producer 3</li>
   <li><input type="checkbox" class="item_name"> Producer 4</li>
   <li><input type="checkbox" class="item_name"> Producer 5</li>
   <li><input type="checkbox" class="item_name"> Producer 6</li>
   <li><input type="checkbox" class="item_name"> Producer 7</li>
</ul>

Here is my jQuery:

function filterList(element){
  var value = $(element).val();

  $("#list > li:not(:contains(" + value + "))").hide();
  $("#list > li:contains(" + value + ")").show();
}

I have also set up a codepen: http://codepen.io/tetonhiker/pen/Nbqrzd

Upvotes: 0

Views: 1204

Answers (2)

jcuenod
jcuenod

Reputation: 58435

Well I've changed your js quite a bit but how about something like this (see the bottom for an explanation):

$("#filter").on("keyup", function() {
	var value = $(this).val().toLowerCase();
	$("#list > li").each(function() {
		$(this).toggle( $(this).text().toLowerCase().indexOf(value) !== -1 )
	});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 id="header">Filter by </h3>
<input id="filter" type="text" name="fname">
<ul class="dropdown-menu gatherDropDown" id="list">
  <li><input type="checkbox" class="item_name">Producer 1</li>
  <li><input type="checkbox" class="item_name">Producer 2</li>
  <li><input type="checkbox" class="item_name">Producer 3</li>
  <li><input type="checkbox" class="item_name">Producer 4</li>
  <li><input type="checkbox" class="item_name">Producer 5</li>
  <li><input type="checkbox" class="item_name">Producer 6</li>
  <li><input type="checkbox" class="item_name">Producer 7</li>
</ul>

Explanation: I'm looping through each of your list items and checking whether their .text() value has a match for the value of the input box. The reason it's not case sensitive is that it makes everything lower case.

Upvotes: 3

RonyLoud
RonyLoud

Reputation: 2436

you can use this also

$.expr[":"].Contains = $.expr.createPseudo(function (arg) {
            return function (elem) {
                return $(elem).text().toLowerCase().indexOf(arg.toLowerCase()) >= 0;
            };
        });
        function filterList(element) {
            var value = $(element).val();
            $("#list > li:not(:Contains(" + value + "))").hide();
            $("#list > li:Contains(" + value + ")").show();
        }

Upvotes: 0

Related Questions