3

Below is JavaScript I'm using for search query there is bug i have found which is issue with letter being caps or lower case. If the letters in list are lower case then it only searches for lower case but if you were to turn the caps on it doesn't find anything. Below are the codes i'm using any help will be appreciated.

HTML

<input type='search' id='search' placeholder='search'> <ul> <li>example 1</li> <li>example 2</li> <li>example 3</li> </ul> 

JavaScript

var search = $("#search"); var listItems = $("li"); search.on("keyup", function () { var terms = search.val(); if (terms == '') { listItems.show(); } else { listItems.hide(); $("li:contains('" + terms + "')").show(); } }); 
1

3 Answers 3

3

You can make the terms lowercase and then search.

var terms = search.val().toLowerCase(); 
Sign up to request clarification or add additional context in comments.

Comments

2

You can overwrite existing jquery contains:

jQuery.expr[':'].contains = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; var search = $("#search"); var listItems = $("li"); search.on("keyup", function () { var terms = search.val(); if (terms == '') { listItems.show(); } else { listItems.hide(); $("li:contains('" + terms + "')").show(); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type='search' id='search' placeholder='search'> <ul> <li>example 1</li> <li>example 2</li> <li>example 3</li> </ul>

Or create a new one:

 jQuery.expr[':'].ncontains = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; var search = $("#search"); var listItems = $("li"); search.on("keyup", function () { var terms = search.val(); if (terms == '') { listItems.show(); } else { listItems.hide(); $("li:ncontains('" + terms + "')").show(); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type='search' id='search' placeholder='search'> <ul> <li>example 1</li> <li>example 2</li> <li>example 3</li> </ul>

3 Comments

thanks alex it worked :) is there better way to improve the search in list?
There are lot search filters out there. For example take a look here phpgang.com/… but i think this one is ok too :)
I would personally recommend using icontains as the name.
2

You may use toLowerCase:

//elsewhere case may vary but here only case is ignored $("li:contains('" + terms.toLowerCase() + "')").show(); 

While you consider using this elsewhere in your code:

//elsewhere case is ignored by transforming lowercase terms to search for var terms = search.val().toLowerCase(); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.