2016-11-08 46 views
0

作为用户输入类型我正在搜索表并显示结果相应。如何使自动完成退格工作在这种情况下

我提出了一个条件来检查,如果输入的输入的长度至少大于或等于2。(但清除值之后其未显示所有数值)

这是我的代码

$('#searchequip').keyup(function(){ 
    if ($(this).val().length >= 2) { 
     $('#errmsgnoequip').hide(); 
     var val = $.trim(this.value).toUpperCase(); 
     var noElem = true; 
     $('.mt-checkbox').each(function(){ 
      var parent = $(this).closest('li'), 
      length = $(this).text().length > 0; 
      if (length && $(this).text().search(new RegExp(val, 'i')) < 0) 
      { 
       parent.fadeOut('slow'); 
      } else { 
       noElem = false; 
       parent.show(); 
      } 
     }); 
     if (noElem) 
      $('#errmsgnoequip').html('No Results Matched').show(); 
    } 
}); 

http://jsfiddle.net/e08o7uct/34/

回答

2

有一个在你的代码小的变化,下面的代码将工作

$('#searchequip').keyup(function(){ 
if ($(this).val().length >= 2) { 
    $('#errmsgnoequip').hide(); 
    var val = $.trim(this.value).toUpperCase(); 
    var noElem = true; 
    $('.mt-checkbox').each(function(){ 
    var parent = $(this).closest('li'), 
    length = $(this).text().length > 0; 
    if (length && $(this).text().search(new RegExp(val, 'i')) < 0) 
    { 
     parent.fadeOut('slow'); 
    }else{ 
     noElem = false; 
     parent.show(); 
    } 
    }); 
    if (noElem) 
    $('#errmsgnoequip').html('No Results Matched').show(); 
    } else { 
     $("#equipdetails li").show(); 
    } 
}) 
1

当值的长度小于2时,您没有执行任何操作。因此不显示隐藏结果。

您可以添加一个else子句到您的长度检查条件。如果值的长度小于2,并且按下的键是退格键,则显示所有内容。 (因此,如果长度为1,但在用户按下一个字母它什么都不做)

$('#searchequip').keyup(function (e){  
    if ($(this).val().length >= 2) { 
     // your filter 
    } else if (e.keyCode == 8){ // 8 = backspace 
     $('.mt-checkbox').closest('li').show(); // show everything hidden 
    } 
} 
1
$('#searchequip').keyup(function(){ 
if ($(this).val().length >= 2) { 
    $('#errmsgnoequip').hide(); 
    var val = $.trim(this.value).toUpperCase(); 
    var noElem = true; 
    $('.mt-checkbox').each(function(){ 
    var parent = $(this).closest('li'), 
    length = $(this).text().length > 0; 
    if (length && $(this).text().search(new RegExp(val, 'i')) < 0) 
    { 
     parent.fadeOut('slow'); 
    }else{ 
     noElem = false; 
     parent.show(); 
    } 
    }); 
    if (noElem) 
    $('#errmsgnoequip').html('No Results Matched').show();  
    } else { 
     $("#equipdetails li").show(); 
     $('#errmsgnoequip').html("");   
    } 
}); 
相关问题