3

enter image description here

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);
         } 

    });
})
  • '#doc_search' is the search field on top
  • '.subdoclist li' are the list items that contain anchor tags with text

At the moment, I have to type exact text and only then the search works.

Fiddle link: Click here

AspiringCanadian
  • 1,595
  • 6
  • 24
  • 43
  • 1
    I switched the logic around a bit here: http://jsfiddle.net/n1wxkhkp/ -- if no input, show all the things, otherwise show each one that contains the string somewhere. – Adam Benzan Dec 14 '15 at 20:37
  • That worked like a charm, you did all the work lol. I'd buy you a beer if you were my colleague, thanks mate. Post this as an answer and I will check it as the answer. – AspiringCanadian Dec 14 '15 at 20:49

3 Answers3

1

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.

Community
  • 1
  • 1
Gonzalo
  • 1,781
  • 15
  • 29
1

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');
   }
});
Adam Benzan
  • 524
  • 3
  • 11
1

Short and case-sensitive variant:

$('#doc_search').on('keyup', function() {
  var inputtext = $(this).val();
  if (inputtext !== '') {
      $('.subdoclist li').each(function() {
         $(this).toggle($("a:contains('"+ inputtext +"')",$(this)).length > 0);
      });
   } else {
     $('.subdoclist li').show();
   }
});
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105