mardi 31 août 2021

pure javascript table checkbox filter

Table filter value with checkbox

I want to match all checkboxes conditions.

Problem : when uncheck and checked again. it compared last value

example: I uncheck robot and re-check james It should not display robot

enter image description here

What I need #

enter image description here

function filter(event, filterCol) {
  let element = event.target;
  let condt1 = document.getElementsByClassName(filterCol);
  var table = document.getElementById("listingTable");
      
    for (let i = 0; i < condt1.length; i++) {
      if (condt1[i].innerHTML.toLocaleUpperCase() == element.value.toLocaleUpperCase()) {
        if (element.checked == true) {
           condt1[i].parentElement.closest('tr').style = "display:table-row"

        } else {
           condt1[i].parentElement.closest('tr').style = "display:none"
        }
      }

  }
}

document.querySelectorAll('.option1').forEach(input => input.addEventListener('input', ()=>filter(event,"check1")));
document.querySelectorAll('.option3').forEach(input => input.addEventListener('input', ()=>filter(event,"check3")));
<div id="input">
<label>Filter Name </label><br>
<label>Adison<input class="option1" type="checkbox" value="Adison" checked/></label>
<label>James<input class="option1" type="checkbox" value="James" checked/></label><br><br>

<label>Filter Race </label><br>
<label>human<input class="option3" type="checkbox" value="human" checked/></label>
<label>robot<input class="option3" type="checkbox" value="robot" checked/></label>
</div><br>


<table id="listingTable">
  <tr>
    <th>Name</th>
    <th>Country</th>
    <th>Race</th>
  </tr>
  <tr>
    <td class="check1">Adison</td>
    <td >Sweden</td>
    <td class="check3">robot</td>
  </tr>
   <tr>
    <td class="check1">Adison</td>
    <td >UK</td>
    <td class="check3">human</td>
  </tr>
   <tr>
    <td class="check1">James</td>
    <td >Sweden</td>
    <td class="check3">human</td>
  </tr>
   <tr>
    <td class="check1">James</td>
    <td>Germany</td>
    <td class="check3">robot</td>
  </tr>
   <tr>
    <td class="check1">Adison</td>
    <td>Italy</td>
    <td class="check3">robot</td>
  </tr>
 
</table>

Or I should modified filter function. Can anyone advise with my code ?

Thank.




Aucun commentaire:

Enregistrer un commentaire