在表格上组合搜索和复选框 javascript 过滤器

Combining search and checkbox javascript filter on table

提问人:Michelle 提问时间:11/6/2023 最后编辑:QuentinMichelle 更新时间:11/9/2023 访问量:71

问:

我在 html 表上有一个搜索过滤器和复选框过滤器,它们都运行良好,但它们可以独立工作。我希望能够检查一个类别,然后使用该类别中的搜索框。现在,如果我开始搜索,复选框会重置,反之亦然。

我认为可能有两种方法可以做到这一点 - 要么更新 GetElement 函数以仅获取显示的内容,要么将两个 if/else 语句合并为一个。但我是自学成才的,这对我来说都是新的,所以我很难编写正确的代码!

  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>

JavaScript jQuery 函数 过滤器 html-table

评论

0赞 SKJ 11/6/2023
你宁愿使用片段来制作现场示例

答:

1赞 Sahab 11/7/2023 #1

让我们看看出了什么问题:

myFunction实际上在每一行上搜索,但根据您的需要,它应该 仅搜索选定的类别

文档内部就绪也逻辑不正确$(this).find("td:eq(1)").html().includes(inputValue.toString())

我们如何解决它:

我们有一个函数,它目前返回一个数组 选中的复选框值,即类别getCheckedItems

getCheckedItems调用文档中的表单,准备仅显示行 选定的类别。文档就绪代码也得到了简化

里面也检查相同的逻辑过滤器只看 所选类别按功能返回myFunctiongetCheckedItems

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></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;
        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];
            let htmlCategory = $(tr[i]).find("td:eq(1)").html();
            if (td) {
                txtValue = td.textContent || td.innerText;
                if (txtValue.toUpperCase().indexOf(filter) > -1 && getCheckedItems().includes(htmlCategory)) {
                    tr[i].style.display = "";
                } else {
                    tr[i].style.display = "none";
                }
            }
        }
    }

    $(document).ready(function() {
        $('input[type="checkbox"]').change(function() {

            $("tr").each(function() {

                let htmlCategory = $(this).find("td:eq(1)").html();
                if(getCheckedItems().includes(htmlCategory)) {
                    $(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;
    }


按关键字或短语搜索:

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

评论

0赞 Wimanicesir 11/7/2023
也许它会起作用。但是,不说你做了什么会使这个答案对其他有同样问题的人毫无用处。
0赞 Sahab 11/7/2023
@Wimanicesir感谢您的评论,我确实从我这边检查了它所要求的问题。而且它肯定会适用于其他所有有更黏糊糊需求的人。请告知您投反对票的原因,以便我在发布答案之前更加小心。
0赞 Wimanicesir 11/8/2023
好吧,另一个答案应该给你一些见解。你应该用语言说出出了什么问题以及你是如何改进/修复它的。这可以是像其他答案一样的列表,也可以在代码中作为注释。另一个人不会有完全相同的代码,但可能会有类似的错误,所以他可以从你的方法中学习。
0赞 Wimanicesir 11/8/2023
此外,如果可能的话,最好有一个工作示例,以便每个人都可以立即验证它是否按预期工作。
1赞 Sahab 11/8/2023
@Wimanicesir非常感谢您的建议。现在,我将尝试包括出了什么问题以及您如何改进/修复它,并尝试发布代码片段运行代码
0赞 Kiran Shahi 11/7/2023 #2

在这里,我对你的代码做了简单的修改。

  1. 我已经添加了它何时从复选框中隐藏。因此,我们可以知道这些项目被复选框隐藏。hidden-cattr
  2. 我用输入事件而不是 keyup 更改了 your 和 bind,以便我也可以处理复制粘贴。myFunction()#myInput
  3. 还添加了类,以便我们可以知道该项目在搜索字段中是隐藏的,我们可以显示使用时按退格键或删除搜索关键字。hidden
  4. 同样,检查您的部分中是否未定义。if(inputValue !== undefined) {}// Select cluster

注意:这只是一个概念验证示例。 您可能需要进行优化和异常处理。

$("#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>