2015-04-30 3 views
4

Я фильтрую таблицу с помощью флажков. Код, который у меня есть, отлично работает в некоторых аспектах.Фильтрующий стол с флажками

Я хочу, чтобы он отфильтровывал результаты, если они отвечают всем чекам, а не одному.

на основе: How can I add to my table filter to allow for multiple checkbox selections, as well as filtering from a dropdown?

Мои Example

$("input[name='filterStatus'], select.filter").change(function() { 
 
    var classes = []; 
 
    var stateClass = "" 
 

 
    $("input[name='filterStatus']").each(function() { 
 
    if ($(this).is(":checked")) { 
 
     classes.push('.' + $(this).val()); 
 
    } 
 
    }); 
 

 
    if (classes == "" && stateClass == "") { 
 
    // if no filters selected, show all items 
 
    $("#StatusTable tbody tr").show(); 
 
    } else { 
 
    // otherwise, hide everything... 
 
    $("#StatusTable tbody tr").hide(); 
 

 
    // then show only the matching items 
 
    rows = $("#StatusTable tr" + stateClass).filter(classes.length ? classes.join(',') : '*'); 
 
    if (rows.size() > 0) { 
 
     rows.show(); 
 
    } 
 
    } 
 

 
});
<html> 
 

 
<head> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 
</head> 
 

 
<body> 
 
    <form name="FilterForm" id="FilterForm" action="" method=""> 
 
    <input type="checkbox" name="filterStatus" value="ISO " /> 
 
    <label for="filter_1">ISO</label> 
 
    <input type="checkbox" name="filterStatus" value="AMCA" /> 
 
    <label for="filter_2">AMCA</label> 
 
    <input type="checkbox" name="filterStatus" value="UL" /> 
 
    <label for="filter_3">UL</label> 
 
    </form> 
 

 
    <table border="1" id="StatusTable"> 
 
    <thead> 
 
     <tr> 
 
     <th>Name</th> 
 
     <th>ISO</th> 
 
     <th>AMCA</th> 
 
     <th>UL</th> 
 
     </tr> 
 
     <tbody> 
 
     <tr class="ISO"> 
 
      <td class="Name">Name1</td> 
 
      <td class="ISO">&#x2713;</td> 
 
      <td class="AMCA">&nbsp;</td> 
 
      <td class="UL">&nbsp;</td> 
 
     </tr> 
 
     <tr class="ISO AMCA"> 
 
      <td class="Name">Name2</td> 
 
      <td class="ISO">&#x2713;</td> 
 
      <td class="AMCA">&#x2713;</td> 
 
      <td class="UL">&nbsp;</td> 
 
     </tr> 
 
     <tr class="ISO AMCA UL"> 
 
      <td class="Name">Name3</td> 
 
      <td class="ISO">&#x2713;</td> 
 
      <td class="AMCA">&#x2713;</td> 
 
      <td class="UL">&#x2713;</td> 
 
     </tr> 
 

 
     </tbody> 
 
    </table> 
 
    <script></script> 
 
</body> 
 

 
</html>

+2

Если вы создали скрипку или размещать код на вашем примере с вашим вопросом было бы проще для других, чтобы помочь вам. – McWayWeb

+1

Будет ли строка всегда содержать правильный список классов своих ячеек? – j08691

+0

Да Я могу назначить строку классу – mHenderson

ответ

5

Измените Jquery, где он перебирает каждую строку. Создайте переменную тега, чтобы сохранить, должна ли строка отображаться, и установить значение по умолчанию true.

Теперь, когда вы будете проходить через каждую строку, вы также будете проходить через каждый класс, который вы проверяете. Если в какой-либо точке тест цикла завершится с ошибкой, установите для отображаемой переменной значение false, чтобы сохранить строку скрытой.

$("input[name='filterStatus']").change(function() { 
 
    var classes = []; 
 

 
    $("input[name='filterStatus']").each(function() { 
 
     if ($(this).is(":checked")) { classes.push('.' + $(this).val()); } 
 
    }); 
 

 
    if (classes == "") { // if no filters selected, show all items 
 
     $("#StatusTable tbody tr").show(); 
 
    } else { // otherwise, hide everything... 
 
     $("#StatusTable tbody tr").hide(); 
 

 
     $("#StatusTable tr").each(function() { 
 
      var show = true; 
 
      var row = $(this); 
 
      classes.forEach(function (className) { 
 
       if (row.find('td' + className).html() == '&nbsp;') { show = false; } 
 
      }); 
 
      if (show) { row.show(); } 
 
     }); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<html> 
 
    
 
    <head> 
 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 
    </head> 
 
    
 
    <body> 
 
     <form name="FilterForm" id="FilterForm" action="" method=""> 
 
      <input type="checkbox" name="filterStatus" value="ISO " /> 
 
      <label for="filter_1">ISO</label> 
 
      <input type="checkbox" name="filterStatus" value="AMCA" /> 
 
      <label for="filter_2">AMCA</label> 
 
      <input type="checkbox" name="filterStatus" value="UL" /> 
 
      <label for="filter_3">UL</label> 
 
     </form> 
 
     <table border="1" id="StatusTable"> 
 
      <thead> 
 
       <tr> 
 
        <th>Name</th> 
 
        <th>ISO</th> 
 
        <th>AMCA</th> 
 
        <th>UL</th> 
 
       </tr> 
 
       <tbody> 
 
        <tr class="ISO"> 
 
         <td class="Name">Name1</td> 
 
         <td class="ISO">&#x2713;</td> 
 
         <td class="AMCA">&nbsp;</td> 
 
         <td class="UL">&nbsp;</td> 
 
        </tr> 
 
        <tr class="ISO AMCA"> 
 
         <td class="Name">Name2</td> 
 
         <td class="ISO">&#x2713;</td> 
 
         <td class="AMCA">&#x2713;</td> 
 
         <td class="UL">&nbsp;</td> 
 
        </tr> 
 
        <tr class="ISO AMCA UL"> 
 
         <td class="Name">Name3</td> 
 
         <td class="ISO">&#x2713;</td> 
 
         <td class="AMCA">&#x2713;</td> 
 
         <td class="UL">&#x2713;</td> 
 
        </tr> 
 
       </tbody> 
 
     </table> 
 
     <script></script> 
 
    </body> 
 

 
</html>

+0

Хорошо работает Спасибо – mHenderson

3

Демо: https://jsfiddle.net/erkaner/u12te5jb/

Вот мое решение

$("input[name='filterStatus']").change(function() { 

var count1 = $("input[name='filterStatus']:checked").length;//number of checked items 

$("#StatusTable>tbody> tr").each(function() {//for each row 
    var count2 = 0;//this is the count of td that has ✓ 
    var row = $(this);//the current row 
    $("input[name='filterStatus']:checked").each(function() {//for each checked item 
     var inputVal = $(this).val();//get the value, which is class of the corresponding td, see below 
     if (row.find('.' + inputVal).html().indexOf("✓") >= 0)//if the td that corresponds to the selected checkbox contains ✓ 
      count2++;//then increase 
    }); 

    if (count1 == count2) //if counts match 
     row.show();//then show 
    else 
     row.hide(); 
    }); 
}); 
+0

Я могу использовать его в скрипке. http://lorencook.com/example/table-1.html Но моя демка плохо – mHenderson

+1

вы можете переместить '' часть в головной части не в теле? – renakre

+0

Нет, что не было спасибо – mHenderson

Смежные вопросы