2012-09-22 5 views
0

J'ai une table de base et je voudrais filtrer les lignes de la table par quelques filtres.Jquery - Filtrer la table par contenu de cellule première lettre

<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> 

filtre d'abord je me suis dit que je pouvais faire quelque chose comme ceci:

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

});​ 

Mais avec le premier filtre lettre je besoin d'aide.

+0

Vous n'expliquez pas quel est le problème avec votre code .. – Nelson

Répondre

3

Essayez cette

$('#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(); 
     } 
    }); 

}); 

Voir la working fiddle

Je suis sûr que cela peut être amélioré pour être plus robuste, mais il devrait vous aider à démarrer

+0

Merci pour ça. Fonctionne très bien. J'ai maintenant deux filtres fonctionnant individuellement. La prochaine étape consiste à essayer de les faire travailler ensemble et de ne pas se substituer les uns aux autres. – 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

Questions connexes