Teton-Coder Teton-Coder - 1 year ago 76
HTML Question

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>

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

Answer Source

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>

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download