带有多个过滤器的过滤表 [英] Filtering table with multiple filters

查看:98
本文介绍了带有多个过滤器的过滤表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下javascript,它接受表单元素的输入,并隐藏不符合搜索条件的表行.

I've got the following javascript which takes the input of a form element, and hides table rows that do not qualify with the search term.

<script>
    function wo_search(filter, column) {
        // Declare variables 
        var input, table, tr, td, i;
        input = document.getElementById("wo_search_type");
        table = document.getElementById("work_order");
        tr = table.getElementsByTagName("tr");

        for (i = 0; i < tr.length; i++) {
            td = tr[i].getElementsByTagName("td")[column];
            if (td) {
                if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
                    tr[i].style.display = "";
                } else {
                    tr[i].style.display = "none";
                }
            }
        }
    }
</script>

问题是,我的表格有7个搜索词,而不仅仅是一个.在我当前的代码中,一次只能使用1个过滤器.选择一个过滤器后,它将在表格中隐藏正确的元素.一旦用户选择了第二个过滤器,第一个过滤器便会失效,基本上会再次显示该过滤器隐藏的所有数据,然后再应用从所选的第二个术语开始的过滤器.

The problem is, my table has 7 search terms, not just one. With my current code, only 1 filter works at a time. When one filter is selected, it will hide the correct elements in the table. As soon as a user selects a 2nd filter, the first filter is nullified, basically all of the data that was hidden by that filter is shown again before applying the filter from the 2nd term selected.

如何使所有过滤器一起应用?

How can I make it so that all of the filters are applied together?

PS

这是根据输入类型来调用过滤器功能的方式,其中包含常规文本输入和选择框.

This is how the filter function is called based on what type of input it is, there are regular text inputs and select boxes.

选择框使用onchange="wo_search(this.value.toUpperCase(), 0)",第二个参数是表列ID.

Select boxes use onchange="wo_search(this.value.toUpperCase(), 0)", the 2nd parameter being the table column id.

输入文本使用onkeyup="wo_search(this.value.toUpperCase(), 0)",第二个参数是表列ID.

Input text uses onkeyup="wo_search(this.value.toUpperCase(), 0)", the 2nd parameter being the table column id.

我不认为我在最初的帖子中说得很清楚,对此我深表歉意,但是有7个不同的输入正试图使表进行过滤.

I don't think I was clear in my initial post, and I apologize for that, but there are 7 different inputs that I am trying to make the table filter for.

基本上,在表格的最顶部有一排(在标题上方),仅包含一个输入框(选择或文本输入),需要过滤表格中的该特定列.

Basically, on the table, there is a row at the very top (Above the headers), that just contain an input box (Select or text input) that need to filter that specific column of the table.

每个列都有自己的过滤器.这是屏幕截图:

Every column has it's own filter. Here is a screenshot:

我认为使用jquery可能更容易,因此也欢迎使用jquery答案.

I'm thinking this may be easier to do with jquery, so jquery answers are also welcome.

推荐答案

在讨论了原始答案的评论后,这就是我得到的.请检查这是否是您需要的.

After talking in the comments of my original answer, here is what I got. Please check to see if this is what you need.

我忘记将要针对过滤器测试的文本小写,这导致了一些时髦的结果.

I had forgotten to lower-case the text that was being tested against the filter, which caused some funky results.

document.addEventListener('DOMContentLoaded', function() {
  var filters = [];
  //the array of current filters;
  var table_data = document.querySelectorAll('#filter-me tbody tr');
  //Gets all table rows in the filter me table

  //Adds an event listener to the filters list element
  document.querySelector('#filter-list').addEventListener('click', function(e) {

    if (!e.target.classList.contains('filter-item')) return false;
    var index = parseInt(e.target.getAttribute('data-index'));
    filters.splice(index, 1);
    update_filters();
    run_filters();
  })

  function value_change(column, e) {
    var action = false;
    //No action has been run
    
    if (e.type == 'keypress') {
      //if the action type is keypress, check to see if we have hit enter AND the value is not empty
      if (e.keyCode == 13 && this.value != '') {
        filters.push({
          column: column,
          filter: this.value.toLowerCase()
        });
        //reset the value
        this.value = '';
        //we have done something through this event, therefore we have action
        action = true;
      }
    } else if (e.type = 'change') {
      //If the event is change, simply push the column index + this select's value
      filters.push({
        column: column,
        filter: this.value.toLowerCase()
      });
      //Again, action is true
      action = true;
    }
    if (action) {
      //Since we have action, we need to update the filters list and run the filters against the table.
      update_filters();
      run_filters();
    }
  }

  //This line is sort of a mess:
  //create an empty array, call the slice method on it, binding it to the document.querySelectorAll('.column-filter') NodeList object
  //loop through each with the actual DOM node itself + it's index
  [].slice.call(document.querySelectorAll('.column-filter')).forEach((filter, i) => {
    filter.addEventListener(filter.tagName.toLowerCase() == 'input' ? 'keypress' : 'change', value_change.bind(filter, i));
    //add the event listener to the correct type -- you may want to be more exact depending on your circumstances on this one to determine which event is added
    //Bind the value_change function to the element, but passing the first element as the index from the element of the nodelist.
  });

  function update_filters() {
    document.querySelector('#filter-list').innerHTML = "";
    //remove all elements;
    var els = filters.map((filter, i) => '<span class="filter-item" data-index="' + i + '">' + filter.filter + '</span>');
    //creates a fake span item here
    document.querySelector('#filter-list').innerHTML = els.join('');
    //joins everything with an empty space and sets the innerHTML to the result
  } // end update_filters

  function run_filters() {
    for (var i = 0, row, tds; row = table_data[i]; i++) {
      //get only the TD elements
      tds = row.querySelectorAll('td');
      //in order for a row to run, every filter must match.
      var pass = filters.every(filter => {
        return tds[filter.column].innerText.toLowerCase().indexOf(filter.filter) != -1;
        //for the filter to match, the TD element in the corresponding column must contain the text
      });
      row.style.display = pass ? '' : 'none'; //if pass, no display styles are added; otherwise, hide them.
    }

  } //end run_filters

});

#filter-list {
  display: inline-block;
}

#filter-list span.filter-item {
  display: inline-block;
  background-color: aqua;
  padding: 3px 6px;
  cursor: pointer;
}

#filter-list span.filter-item+span.filter-item {
  margin-left: 5px;
}

#filter-list span.filter-item::after {
  content: 'x';
  margin-left: 4px;
  padding-left: 4px;
  border-left: 1px solid grey;
}

<table id="filter-me" class="table">
  <caption id="filter-list"></caption>
  <thead>
    <tr>
      <th>
        <select class="column-filter">
          <option value="">&nbsp;</option>
          <option value="lorem">Lorem</option>
          <option value="illum">Illum</option>
        </select>
      </th>
      <th><input type="search" placeholder="Filter" class="column-filter"></th>
      <th><input type="search" placeholder="Filter" class="column-filter"></th>
      <th><input type="search" placeholder="Filter" class="column-filter"></th>
      <th><input type="search" placeholder="Filter" class="column-filter"></th>
    </tr>
    <tr>
      <th>Lorem, ipsum. <span class="arrow-up">&nbsp;</span></th>
      <th>Dolores, tempora?</th>
      <th>Tempore, soluta?</th>
      <th>Commodi, illum!</th>
      <th>Laudantium, debitis!</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Lorem ipsum dolor sit amet.</td>
      <td>Magni aspernatur eveniet amet. Eos.</td>
      <td>Doloribus numquam at nisi fuga.</td>
      <td>Exercitationem libero saepe iusto labore!</td>
      <td>Quod, debitis. Hic, eius voluptates?</td>
    </tr>
    <tr>
      <td>Excepturi aspernatur quia sequi labore.</td>
      <td>Ad tempore laudantium sed temporibus.</td>
      <td>Officia accusamus architecto perferendis quod?</td>
      <td>Laudantium facilis numquam quas iusto!</td>
      <td>Doloribus tenetur deleniti voluptatum alias.</td>
    </tr>
    <tr>
      <td>Ratione suscipit quis repudiandae ipsam!</td>
      <td>Repellendus blanditiis iure vel delectus.</td>
      <td>Sunt debitis voluptatum consectetur aliquam!</td>
      <td>Libero expedita odio maiores optio!</td>
      <td>Nam molestias delectus quam porro.</td>
    </tr>
    <tr>
      <td>Earum delectus sint ab error?</td>
      <td>Dicta ipsam facilis optio aliquam?</td>
      <td>Blanditiis eligendi sit ad accusamus?</td>
      <td>Sequi laborum illo eos incidunt?</td>
      <td>Necessitatibus iure sequi eaque quam!</td>
    </tr>
    <tr>
      <td>Illum aspernatur fuga laborum ratione!</td>
      <td>Maiores, excepturi! Dolorum, aspernatur mollitia.</td>
      <td>Labore corrupti itaque provident adipisci.</td>
      <td>Ipsum ducimus earum minus fuga.</td>
      <td>Necessitatibus rerum molestias autem libero.</td>
    </tr>
    <tr>
      <td>Nemo omnis similique labore minima!</td>
      <td>Dolore dolores saepe ea adipisci.</td>
      <td>Voluptate iusto in unde quas.</td>
      <td>Quod aperiam sit ut iusto.</td>
      <td>Quidem quisquam cupiditate dolor officiis.</td>
    </tr>
    <tr>
      <td>Officia numquam aliquam qui nulla.</td>
      <td>Laboriosam repellendus soluta aliquid similique.</td>
      <td>Veritatis, neque porro? Quae, quia?</td>
      <td>Magnam vel autem ad blanditiis!</td>
      <td>Laboriosam, a. Sunt, suscipit deserunt!</td>
    </tr>
    <tr>
      <td>Aspernatur iste saepe beatae nam.</td>
      <td>Ducimus quisquam corrupti quam inventore?</td>
      <td>Sit ullam minus possimus quidem!</td>
      <td>Officiis laborum laudantium veritatis et!</td>
      <td>Impedit dignissimos dolores maxime sequi.</td>
    </tr>
    <tr>
      <td>Neque similique cum sequi unde!</td>
      <td>Voluptatibus, ad? Ullam, facilis cumque.</td>
      <td>Enim in magnam id illo!</td>
      <td>Ex nobis quidem voluptatem voluptate.</td>
      <td>Eligendi esse ipsa ipsam omnis!</td>
    </tr>
    <tr>
      <td>Neque, fugit. Tempora, voluptates vel.</td>
      <td>Officia cupiditate dolores magni sunt?</td>
      <td>Eveniet tempore illo ipsa? Non.</td>
      <td>Possimus repellendus eligendi ipsam necessitatibus!</td>
      <td>Quisquam natus eos omnis ea.</td>
    </tr>
    <tr>
      <td>Aliquam voluptas recusandae et animi?</td>
      <td>Quis distinctio officiis quisquam dolores.</td>
      <td>Repellendus suscipit vero delectus hic.</td>
      <td>Quae asperiores temporibus impedit quis.</td>
      <td>Temporibus ipsa quidem magnam odio.</td>
    </tr>
    <tr>
      <td>Voluptatem optio quas nesciunt debitis!</td>
      <td>Hic mollitia alias laborum accusantium?</td>
      <td>Obcaecati eaque corrupti aperiam culpa!</td>
      <td>Voluptatum sequi sed numquam eos!</td>
      <td>Laborum exercitationem deleniti quaerat dolorem.</td>
    </tr>
    <tr>
      <td>Modi nam asperiores totam excepturi.</td>
      <td>Quod ipsa dolorem magni labore.</td>
      <td>Qui quidem quod eum quasi!</td>
      <td>Explicabo, ut eveniet. Quos, nam?</td>
      <td>Harum fugit sequi blanditiis accusamus.</td>
    </tr>
    <tr>
      <td>Ullam dolores vel natus in?</td>
      <td>Dolor velit dolorum quos error!</td>
      <td>Obcaecati blanditiis natus aperiam esse.</td>
      <td>Consequatur quasi qui minima laboriosam.</td>
      <td>Voluptatum, et atque. Iste, earum?</td>
    </tr>
    <tr>
      <td>Voluptate esse placeat doloribus hic?</td>
      <td>Dolorum velit ab incidunt quam.</td>
      <td>Laboriosam facere sed quia nisi.</td>
      <td>Saepe ex officia libero beatae?</td>
      <td>Ipsam ab distinctio assumenda itaque!</td>
    </tr>
    <tr>
      <td>Perferendis facere natus accusantium ut.</td>
      <td>Ipsam possimus dolores corporis totam!</td>
      <td>Ab officia rerum tempora ipsum.</td>
      <td>Id, soluta neque! Voluptatibus, id.</td>
      <td>Eaque enim fugiat corporis velit!</td>
    </tr>
    <tr>
      <td>Voluptatum cum atque eos quod.</td>
      <td>Esse corporis mollitia voluptatem ipsum.</td>
      <td>Corrupti unde inventore similique ad?</td>
      <td>Blanditiis dolorum molestiae minus tempore.</td>
      <td>Temporibus nihil doloremque quibusdam! Voluptatem!</td>
    </tr>
    <tr>
      <td>Iste voluptates iusto facilis cum?</td>
      <td>At est necessitatibus architecto repellendus?</td>
      <td>Officia qui soluta veniam nemo.</td>
      <td>Nobis cupiditate officiis reiciendis possimus.</td>
      <td>Voluptatibus quidem assumenda adipisci quis.</td>
    </tr>
    <tr>
      <td>Illum voluptatibus reprehenderit repellendus nostrum?</td>
      <td>Distinctio natus harum est nulla?</td>
      <td>Temporibus sit consequatur delectus ducimus.</td>
      <td>Veniam possimus qui fugiat temporibus.</td>
      <td>Delectus tenetur asperiores quasi perspiciatis.</td>
    </tr>
    <tr>
      <td>Quod atque ut doloribus libero?</td>
      <td>Animi assumenda praesentium alias accusantium!</td>
      <td>Labore ex optio eveniet architecto.</td>
      <td>Eaque delectus nemo fugiat dolorum.</td>
      <td>Atque, delectus. Obcaecati, saepe veritatis.</td>
    </tr>
  </tbody>
</table>

这篇关于带有多个过滤器的过滤表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆