
I am trying to add a search filter so that user can find results from this list of contracts while they are typing. E.g.: if a user types "IP", then the top 4 results should be displayed. Following is the function:
$('#doc_search').on('keyup', function(){
var inputtext = $(this).val().toLowerCase();
$('.subdoclist li a').each(function() {
if(inputtext ==''){
$('.subdoclist li').each(function(){
$(this).addClass('show');
});
console.log(inputtext);
} else if ($(this).text().toLowerCase() === inputtext) {
$('.subdoclist li').removeClass('show');
$(this).parent().addClass('show');
console.log(inputtext);
}
});
})
At the moment, I have to type exact text and only then the search works.
Fiddle link: Click here
Here it is with a couple of things fixed up, first I'm using indexOf > -1 to see if the input string is contained within each potential match, and instead of removing show on all of them per-match I do it before it performs the search.
$('#doc_search').on('keyup', function() {
var inputtext = $(this).val().toLowerCase();
if (inputtext != '') {
$('.subdoclist li').removeClass('show');
$('.subdoclist li a').each(function() {
if ($(this).text().toLowerCase().indexOf(inputtext) > -1) {
$(this).parent().addClass('show');
}
});
} else {
$('.subdoclist li').addClass('show');
}
});
If you want a simple search, you can check if the text entered is contained on the string like this: How to check whether a string contains a substring in JavaScript?
You can check each word entered on the search, splitting the string with space delimiter and using a loop but that will take more effort if there too words or a lot if entries.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With