2012-09-22 26 views
0

我有一個基本的表,並希望通過幾個過濾器過濾錶行。jquery - 過濾表格按行單元格內容第一個字母

<select id="location"> 
    <option value="New York">New York</option>        
    <option value="LA">LA</option> 
    <option value="Boston">Boston</option> 
</select> 
<select id="last-name"> 
    <option>Last name</option> 
    <option value="ABCDE">A-E</option> 
    <option value="FGHIJ">F-J</option> 
    <option value="KLMNO">K-O</option> 
    <option value="PQRST">P-T</option> 
    <option value="UVWXYZ">U-Z</option> 
</select> 
<table id="personnel"> 
    <thead> 
     <tr> 
      <th>First Name</th> 
      <th>Last Name</th> 
      <th>Location</th> 
     </tr> 
    </thead> 
    <tbody> 
     <tr> 
      <td class="firstname">Abel</td> 
      <td class="lastname">Alpha</td> 
      <td class="location">LA</td> 
     </tr> 
     <tr> 
      <td class="firstname">Benny</td> 
      <td class="lastname">Bravo</td> 
      <td class="location">New York</td> 
     </tr> 
     <tr> 
      <td class="firstname">Cindy</td> 
      <td class="lastname">Charlie</td> 
      <td class="location">Boston</td> 
     </tr> 
    <tbody> 
</table> 

第一濾波器我想我可以做這樣的事情:

$(function() {  
    $('#location').change(function() { 
     $("#personnel td.location:contains('" + $(this).val() + "')").parent().show(); 
     $("#personnel td.location:not(:contains('" + $(this).val() + "'))").parent().hide(); 
    }); 

});​ 

但隨着第一個字母過濾器,我需要一些幫助。

+0

你不解釋你的代碼有什麼問題。 – Nelson

回答

3

試試這個

$('#last-name').change(function() { 
    var curr = $(this).val(); 
    $("#personnel td.lastname").each(function(){ 
     if(curr.indexOf($(this).text().substr(0,1)) != -1){ //Check if first letter exists in the drop down value 
      $(this).parent().show(); 

     }else{ 
      $(this).parent().hide(); 
     } 
    }); 

}); 

working fiddle

我相信這可以提高更強勁,但它應該讓你開始

+0

謝謝你。很棒。我現在有兩個獨立工作的過濾器。下一步是嘗試讓他們一起工作,而不是互相重疊。 – teeraina

1
$('#last-name').change(function() { 
    var val = this.value; 

    // with a single chain 
    $("#personnel td.lastname") 
     .parent() 
     .hide() 
     .end() // jump to td.lastname 
     .filter(function() { 
      var firstChar = $(this).text()[0]; // pick first character 
      return val.indexOf(firstChar) >= 0; 
     }) 
     .parent() 
     .show(); 
});​ 

The demo

相關問題