2016-10-18 20 views
0

我有一個表格和一個搜索輸入。如何根據兩個值搜索表格tr

當用戶鍵入的東西輸入,我需要顯示與搜索輸入

用戶可以搜索或者通過公司名稱CEO的名字裏面輸入的值相關的信息

// if user enters TCS or Chandran ,i need to show TCS table row 
    $("#search").keyup(function(){ 
     _this = this; 
     $.each($(".portlet"), function() { 
      if($(this).data('compname').toLowerCase().indexOf($(_this).val().toLowerCase()) === -1) 
       $(this).hide(); 
      else 
       $(this).show();     
     }); 
    }); 

http://jsfiddle.net/cod7ceho/173/

可否請你讓我知道如何解決這個

+0

,沒有桌子,只是div的和列表。在任何地方都沒有'tr'元素。也沒有任何具有'data-compname'屬性的元素。你寫了這個代碼嗎?它與示例HTML絕對沒有關係。不奇怪它不起作用。 – ADyson

+0

有一個以

Pawan

+0

yes,有一張表。但是沒有'tr's這就是你想要搜索的東西。 'tbody'中唯一有效的元素是'tr'。你不應該把div放在那裏。您的HTML無效。 – ADyson

回答

1

增加了一個條件:

if((($(this).data('compname').toLowerCase().indexOf($(_this).val().toLowerCase())) === 0)||($(this).data('ceo').toLowerCase().indexOf($(_this).val().toLowerCase())===0)) 

看看這個小提琴: http://jsfiddle.net/cod7ceho/177/

在小提琴
+0

完美工作,非常感謝。 – Pawan

+0

快樂。乾杯!! –

0

你只想隱藏「行」,如果你不能找到兩個compnameceo搜索字符串,所以你應該添加

&& ($(this).data('ceo').toLowerCase().indexOf($(_this).val().toLowerCase()) === -1)if

像這樣:

if(($(this).data('compname').toLowerCase().indexOf($(_this).val().toLowerCase()) === -1) && ($(this).data('ceo').toLowerCase().indexOf($(_this).val().toLowerCase()) === -1))

這有點難以閱讀,所以我也會重新格式化爲:

if(
    ($(this).data('compname').toLowerCase().indexOf($(_this).val().toLowerCase()) === -1) 
    && ($(this).data('ceo').toLowerCase().indexOf($(_this).val().toLowerCase()) === -1) 
){ 
    $(this).hide(); 
} else ... 
+0

謝謝,但未被捕獲SyntaxError:意外的令牌&& – Pawan

+0

這可能是一個括號問題,你現在看起來像'012'如果(你聲明)&&(mystatement)' 當它應該是 '如果((你說)&&(mystatement))' – narvoxx

0

您可以使用jQuery filter(),例如:

$("#search").keyup(function() { 
    _this = this; 
    inputVal = $(this).val().toLowerCase(); 
    console.log(inputVal); 
    if (inputVal === "") { 
    $('.portlet').fadeIn(); 
    } else { 
    $('.portlet').filter(function() { 
     return $(this).data('compname').toLowerCase().indexOf($(_this).val().toLowerCase()) !== -1; 
    }).fadeIn(); 
    $('.portlet').filter(function() { 
     return $(this).data('compname').toLowerCase().indexOf($(_this).val().toLowerCase()) == -1; 
    }).fadeOut(); 
    } 
}); 

小提琴:http://jsfiddle.net/cod7ceho/182/

+0

謝謝,但它不工作 – Pawan

+0

你是什麼意思?我已經過測試,看起來很好......它可以過濾公司名稱,但您也可以修改以便由首席執行官進行過濾。 – DouglasCamargo

+0

你能否提供一個樣品小提琴 – Pawan

0

我去以下方式:

$("#search").keyup(function(){ 
    _found = false; 
    _this = this; 
    $.each($(".portlet"), function() { 
     if($(this).data('compname').toLowerCase().indexOf($(_this).val().toLowerCase()) == -1) { 
      $(this).hide(); 
      _found = false; 
     } else { 
      $(this).show(); 
      _found = true; 
     } 

     if($(this).data('ceo').toLowerCase().indexOf($(_this).val().toLowerCase()) == -1 && _found == false) 
      $(this).hide(); 
     else 
      $(this).show(); 
    }); 
}); 

我加入了可變_found的狀態保持器和附加條件。合適的不是最好的方式,它只是在工作。