2016-11-08 49 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("");   
    } 
}); 
相關問題