skip to Main Content

I have a search filter and checkbox filter on an html table that are both working well, but they work independently. I would like to be able to check a category, and then use the search box within that category. Right now, if I start searching, the checkbox resets and vice versa.

I think there may be two ways to do this – either update the GetElement functions to only fetch what is displayed, or to combine the two if/else statements into one. But I’m self-taught and this is all new to me so I’m having trouble writing the correct code!

  function myFunction() {
    var input, filter, table, tr, td, i, txtValue;
    input = document.getElementById("myInput");
    filter = input.value.toUpperCase();
    table = document.getElementById("myTable");
    tr = table.getElementsByTagName("tr");
    for (i = 0; i < tr.length; i++) {
      td = tr[i].getElementsByTagName("td")[0];
      if (td) {
        txtValue = td.textContent || td.innerText;
        if (txtValue.toUpperCase().indexOf(filter) > -1) {
          tr[i].style.display = "";
        } else {
          tr[i].style.display = "none";
        }
      }
    }
  } 
src = "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"

  // Select cluster
  $(document).ready(function() {
    $('input[type="checkbox"]').change(function() {
      var inputValue = $(this).attr("value");
      var checked = $(this)[0].checked;
      $("tr").each(function() {
        if ($(this).find("td:eq(1)").html() !== undefined && $(this).find("td:eq(1)").html().includes(inputValue.toString())) {
          if (checked) {
            $(this).show(); // slice by n numbers here
          } else {
            $(this).hide();
          }
        }
      });
    });
  });

function checkedAll() {
  console.log("All")
  var elements = this.form.getElementsByTagName('input');
  console.log(elements)
  // iterate and change status
  for (var i = elements.length; i--;) {
    if (elements[i].type == 'checkbox') {
      console.log(this)
      elements[i].checked = this.checked;
      $(elements[i]).trigger("change");
    }
  }
} 
table#myTable {
  width: 800px;
}
<!-- SEARCH -->

<h3>Search by keyword or phrase:</h3>
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Start typing to filter the table below" style="width:100%; transform: none;">


<!-- CHECKMARKS -->


<form action="" method="post" name="frm1" id="frm1">

  <h3>Filter by category:</h3>

  <label class="clickable">
<input type="checkbox" name="cluster_ids" id="cluster_ids" onclick="checkedAll.call(this);" checked /> Select all</label><br>

  <div style="float:left; width:33%; min-width:200px;">
    <label class="clickable">
<input value="For attorneys" type="checkbox" name="cluster_ids" checked/> For attorneys</label><br>

    <label class="clickable">
<input value="For clinicians" type="checkbox" name="cluster_ids" checked/> For clinicians</label><br>

    <label class="clickable">
<input value="For patients and families" type="checkbox" name="cluster_ids" checked/> For patients and families</label><br>


    <!-- TABLE -->

    <table id="myTable">
      <tr>
        <th>
          <h1>Resource</h1>
        </th>
        <th>
          <h1>Category</h1>
        </th>
      </tr>

      <tr>
        <td>
          <h3>20 things patients can do to help prevent medical errors</h3>
          <p>Information for patients from the Agency for Healthcare Research and Quality (AHRQ)</p>
        </td>
        <td class="topic-column">For patients and families</td>
      </tr>

      <tr>
        <td>
          <h3>Best practices for attorneys representing patients using CARe</h3>
          <p>How lawyers can best support patients during the CARe process</p>
        </td>

        <td class="topic-column">For attorneys</td>

        <tr>
          <td>
            <h3>Clinician CARe communication algorithm</h3>
            <p>Flow chart with examples of what to say and what not to say during conversations with patients and families</p>
          </td>
          <td class="topic-column">For clinicians</td>
        </tr>

        <tr>
          <td>
            <h3>Guidelines for handling medical adverse events: Enhancing safety through candid communication</h3>
            <p>Covers the seven aspects of response to adverse events: initial response, truth-telling, apologies, mediation, root cause analysis, compensation, and reporting</p>
          </td>
          <td class="topic-column">For clinicians</td>
        </tr>

        <tr>
          <td>
            <h3>Handout for patients</h3>
            <p>A patient-focused flyer that explains the elements of CARe</p>
          </td>
          <td class="topic-column">For patients and families</td>
        </tr>

    </table>

2

Answers


  1. i have updated your code , hope this will fix your issue.

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
    
    
    function getCheckedItems() {
        let checkboxValues = [];
        
        $('input[type="checkbox"]').each(function(index) {
             let inputValue = $(this).attr("value");
             if( $(this).is(':checked') && inputValue ){
            checkboxValues.push(inputValue);
         }
       
        });
        
        return checkboxValues;
    } 
    
    
    function myFunction() {
        var input, filter, table, tr, td, i, txtValue,tdCategory,txtValueCategory;
        input = document.getElementById("myInput");
        filter = input.value.toUpperCase();
        table = document.getElementById("myTable");
        tr = table.getElementsByTagName("tr");
        for (i = 0; i < tr.length; i++) {
          td = tr[i].getElementsByTagName("td")[0];
          tdCategory = tr[i].getElementsByTagName("td")[1];
          if(tdCategory) {
            txtValueCategory = tdCategory.textContent || tdCategory.innerText;        
                 
          }
          
          if (td) {
            txtValue = td.textContent || td.innerText;
            if (  txtValue.toUpperCase().indexOf(filter) > -1 &&   txtValueCategory.includes(txtValueCategory)) {
              tr[i].style.display = "";
            } else {
              tr[i].style.display = "none";
            }
          }
        }
      } 
    //src = "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"
    
    
    
      // Select cluster
      $(document).ready(function() {
        $('input[type="checkbox"]').change(function() {
          var inputValue = $(this).attr("value");
          var checked = $(this)[0].checked;
          
          $("tr").each(function() {
          
            if(inputValue) {
            
            if ($(this).find("td:eq(1)").html() !== undefined && $(this).find("td:eq(1)").html().includes(inputValue.toString())
             && getCheckedItems().includes($(this).find("td:eq(1)").html())
            ) {
             debugger
              if (checked) {
                $(this).show(); // slice by n numbers here
                myFunction();
              } else {
                $(this).hide();
              }
            }
            }
            
            
            
          });
        });
      });
    
    function checkedAll() {
      console.log("All")
      var elements = this.form.getElementsByTagName('input');
      console.log(elements)
      // iterate and change status
      for (var i = elements.length; i--;) {
        if (elements[i].type == 'checkbox') {
          console.log(this)
          elements[i].checked = this.checked;
          $(elements[i]).trigger("change");
        }
      }
      
    } 
    
    
    
    </script>
    
    <style> 
    table#myTable {
      width: 800px;
    }
    
    
    </style>
    
    
    <!-- SEARCH -->
    
    <h3>Search by keyword or phrase:</h3>
    <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Start typing to filter the table below" style="width:100%; transform: none;">
    
    
    <!-- CHECKMARKS -->
    
    
    <form action="" method="post" name="frm1" id="frm1">
    
      <h3>Filter by category:</h3>
    
      <label class="clickable">
    <input type="checkbox" name="cluster_ids" id="cluster_ids" onclick="checkedAll.call(this);" checked /> Select all</label><br>
    
      <div style="float:left; width:33%; min-width:200px;">
        <label class="clickable">
    <input value="For attorneys" type="checkbox" name="cluster_ids" checked/> For attorneys</label><br>
    
        <label class="clickable">
    <input value="For clinicians" type="checkbox" name="cluster_ids" checked/> For clinicians</label><br>
    
        <label class="clickable">
    <input value="For patients and families" type="checkbox" name="cluster_ids" checked/> For patients and families</label><br>
    
    
        <!-- TABLE -->
    
        <table id="myTable">
          <tr>
            <th>
              <h1>Resource</h1>
            </th>
            <th>
              <h1>Category</h1>
            </th>
          </tr>
    
          <tr>
            <td>
              <h3>20 things patients can do to help prevent medical errors</h3>
              <p>Information for patients from the Agency for Healthcare Research and Quality (AHRQ) apologies</p>
            </td>
            <td class="topic-column">For patients and families</td>
          </tr>
    
          <tr>
            <td>
              <h3>Best practices for attorneys representing patients using CARe</h3>
              <p>How lawyers can best support patients during the CARe process</p>
            </td>
    
            <td class="topic-column">For attorneys</td>
    
            <tr>
              <td>
                <h3>Clinician CARe communication algorithm</h3>
                <p>Flow chart with examples of what to say and what not to say during conversations with patients and families</p>
              </td>
              <td class="topic-column">For clinicians</td>
            </tr>
    
            <tr>
              <td>
                <h3>Guidelines for handling medical adverse events: Enhancing safety through candid communication</h3>
                <p>Covers the seven aspects of response to adverse events: initial response, truth-telling, apologies, mediation, root cause analysis, compensation, and reporting</p>
              </td>
              <td class="topic-column">For clinicians</td>
            </tr>
    
            <tr>
              <td>
                <h3>Handout for patients</h3>
                <p>A patient-focused flyer that explains the elements of CARe</p>
              </td>
              <td class="topic-column">For patients and families</td>
            </tr>
    
        </table>
    
    Login or Signup to reply.
  2. Here, I have made simple twist to your code.

    1. I have added hidden-cat to tr when it is hidden from checkbox. So, that we can know that those items are hidden by checkbox.
    2. I changed your myFunction() and bind #myInput with input event instead of keyup so that I can handle copy paste also.
    3. Also added hidden class so that we can know that item is hidden from search field and we can show that when use press backspace or remove the search keyword.
    4. Similarly, checked if undefined by if(inputValue !== undefined) {} in your // Select cluster section.

    Note: This is a just proof of concept example. You might need to work on optimization and exception handling.

    $("#myInput").off("input").on("input", function() {
      var inputValue = $(this).val();
      if (inputValue === "") {
        $("tr:not(.header, .hidden-cat)").removeClass('hidden').show();
        return;
      }
      $("tr:not(.header,.hidden-cat)").addClass('hidden').hide();
      $("#myTable").find("tr:not(.header, .hidden-cat)").each(function() {
        let $this = $(this);
        if ($this.text().toLowerCase().indexOf(inputValue.toLowerCase()) > -1) {
          $this.removeClass('hidden').show();
        }
      });
    });
    src = "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"
    
    // Select cluster
    $(document).ready(function() {
      $('input[type="checkbox"]').change(function() {
        var inputValue = $(this).attr("value");
        var checked = $(this)[0].checked;
        $("tr").each(function() {
          if (inputValue !== undefined) {
            if ($(this).find("td:eq(1)").html() !== undefined && $(this).find("td:eq(1)").html().includes(inputValue.toString())) {
              if (checked) {
                $(this).removeClass("hidden-cat").show(); // slice by n numbers here
              } else {
                $(this).addClass("hidden-cat").hide();
              }
            }
          }
        });
      });
    });
    
    function checkedAll() {
      //console.log("All")
      var elements = this.form.getElementsByTagName('input');
      //console.log(elements)
      // iterate and change status
      for (var i = elements.length; i--;) {
        if (elements[i].type == 'checkbox') {
          //console.log(this)
          elements[i].checked = this.checked;
          $(elements[i]).trigger("change");
        }
      }
    }
    table#myTable {
      width: 800px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <!-- SEARCH -->
    
    <h3>Search by keyword or phrase:</h3>
    <input type="text" id="myInput" placeholder="Start typing to filter the table below" style="width:100%; transform: none;">
    
    
    <!-- CHECKMARKS -->
    
    
    <form action="" method="post" name="frm1" id="frm1">
    
      <h3>Filter by category:</h3>
    
      <label class="clickable">
    <input type="checkbox" name="cluster_ids" id="cluster_ids" onclick="checkedAll.call(this);" checked /> Select all</label><br>
    
      <div style="float:left; width:33%; min-width:200px;">
        <label class="clickable">
    <input value="For attorneys" type="checkbox" name="cluster_ids" checked/> For attorneys</label><br>
    
        <label class="clickable">
    <input value="For clinicians" type="checkbox" name="cluster_ids" checked/> For clinicians</label><br>
    
        <label class="clickable">
    <input value="For patients and families" type="checkbox" name="cluster_ids" checked/> For patients and families</label><br>
    
    
        <!-- TABLE -->
    
        <table id="myTable">
          <tr class="header">
            <th>
              <h1>Resource</h1>
            </th>
            <th>
              <h1>Category</h1>
            </th>
          </tr>
    
          <tr>
            <td>
              <h3>20 things patients can do to help prevent medical errors</h3>
              <p>Information for patients from the Agency for Healthcare Research and Quality (AHRQ)</p>
            </td>
            <td class="topic-column">For patients and families</td>
          </tr>
    
          <tr>
            <td>
              <h3>Best practices for attorneys representing patients using CARe</h3>
              <p>How lawyers can best support patients during the CARe process</p>
            </td>
    
            <td class="topic-column">For attorneys</td>
    
            <tr>
              <td>
                <h3>Clinician CARe communication algorithm</h3>
                <p>Flow chart with examples of what to say and what not to say during conversations with patients and families</p>
              </td>
              <td class="topic-column">For clinicians</td>
            </tr>
    
            <tr>
              <td>
                <h3>Guidelines for handling medical adverse events: Enhancing safety through candid communication</h3>
                <p>Covers the seven aspects of response to adverse events: initial response, truth-telling, apologies, mediation, root cause analysis, compensation, and reporting</p>
              </td>
              <td class="topic-column">For clinicians</td>
            </tr>
    
            <tr>
              <td>
                <h3>Handout for patients</h3>
                <p>A patient-focused flyer that explains the elements of CARe</p>
              </td>
              <td class="topic-column">For patients and families</td>
            </tr>
    
        </table>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search