UnKnown UnKnown - 1 month ago 9
jQuery Question

How to make auto Complete list show after entering atleast 2 characters

As User types in the input i am searching the table and displaying results accordingly .

Could you please tell me , if the length of the entered input is at least greater than or equal to 2

This is my code

$(document).ready(function(){
$('#filtertags').keyup(function(){
$('#errmsgnotags').hide();
var noElemtag = true;
var val = $.trim(this.value).toLowerCase();
var tr = $('#tagstable tbody td');
el = tr.find('label').filter(function(){
return this.innerHTML.toLowerCase().indexOf(val) >= 0;
}).closest('td');
if (el.length >= 1) {
noElemtag = false;
}
tr.not(el).fadeOut();
el.fadeIn();
if (noElemtag)
$('#errmsgnotags').html('No Results Matched').show();
})
});


http://jsfiddle.net/e08o7uct/17/

Answer

Just check the length of your input element on keyup event and show or hide tags based on your value.

Updated code

$('#filtertags').keyup(function() {
    var tr = $('#tagstable tbody td');//keep this outside as we have to show all elements on backspace
    if ($(this).val().length >= 2) {
      $('#errmsgnotags').hide();
      var noElemtag = true;
      var val = $.trim(this.value).toLowerCase();

      el = tr.find('label').filter(function() {
        return this.innerHTML.toLowerCase().indexOf(val) >= 0;
      }).closest('td');
      if (el.length >= 1) {
        noElemtag = false;
      }
      tr.not(el).fadeOut();
      el.fadeIn();
      if (noElemtag) $('#errmsgnotags').html('No Results Matched').show();
    } else {
      tr.fadeIn(); //show all if length does not match the required number of characters
      $('#errmsgnotags').hide();
    }
})

UPDATED FIDDLE