Фильтр JQuery на основе совпадения текста в строке

Я новичок в JQuery. У меня ниже HTML:

<div class = "search-button">
   <label for = "filter">Store Name:</label>
   <select class = "filter" data-tableId = "table1" onchange = "testFilter()">
  <option value = "all">All Stores</option>
  <option value = "United Kingdom">United Kingdom</option>
  <option value = "United States">United States</option>
  <option value = "France">France</option>
  <option value = "Denmark">Denmark</option>
  <option value = "Ireland">Ireland</option>
   </select>
</div>

<div id = "recordContent">
   <table id = "orderTable">
  <tbody>
     <tr>
        <th>Store Name</th>
        <th>Language Code</th>
        <th>Testcase Name</th>
        <th>Order Id</th>
        <th>Order Total</th>
        <th>Order Date</th>
     </tr>
     <tr class = "record">
        <td class = "store">ireland</td>
        <td class = "langCode">en_IE</td>
        <td class = "tcName">Guest User Checkout - Credit Card</td>
        <td class = "orderID">4001820209</td>
        <td class = "orderTotal">19.98</td>
        <td class = "orderDate">12-02-2019 15:37:30.201</td>
     </tr>
     <tr></tr>
     <tr class = "record">
        <td class = "store">denmark</td>
        <td class = "langCode">en_DK</td>
        <td class = "tcName">Guest User Checkout - Credit Card</td>
        <td class = "orderID">6001825084</td>
        <td class = "orderTotal">338 DKK</td>
        <td class = "orderDate">12-02-2019 15:37:35.140</td>
     </tr>
     <tr></tr>
     <tr class = "record">
        <td class = "store">united_kingdom</td>
        <td class = "langCode">en_GB</td>
        <td class = "tcName">Guest User Checkout - Credit Card</td>
        <td class = "orderID">7002541022</td>
        <td class = "orderTotal">13.04</td>
        <td class = "orderDate">12-02-2019 15:45:08.038</td>
     </tr>
     <tr></tr>
     <tr class = "record">
        <td class = "store">united_states</td>
        <td class = "langCode">en_US</td>
        <td class = "tcName">Guest User Checkout - Credit Card</td>
        <td class = "orderID">2001741036</td>
        <td class = "orderTotal">69.90</td>
        <td class = "orderDate">12-02-2019 15:46:33.310</td>
     </tr>
     <tr></tr>
     <tr class = "record">
        <td class = "store">united_kingdom</td>
        <td class = "langCode">en_GB</td>
        <td class = "tcName">Registered User Checkout - Paypal</td>
        <td class = "orderID">7002541028</td>
        <td class = "orderTotal">8.14</td>
        <td class = "orderDate">12-02-2019 15:50:04.713</td>
     </tr>
     <tr></tr>
     <tr class = "record">
        <td class = "store">united_states</td>
        <td class = "langCode">en_US</td>
        <td class = "tcName">Registered User Checkout - Paypal</td>
        <td class = "orderID">2001741030</td>
        <td class = "orderTotal">15.98</td>
        <td class = "orderDate">12-02-2019 15:51:23.551</td>
     </tr>
     <tr></tr>
     <tr class = "record">
        <td class = "store">france</td>
        <td class = "langCode">en_FR</td>
        <td class = "tcName">Guest User Checkout - Credit Card</td>
        <td class = "orderID">11002001160</td>
        <td class = "orderTotal">35.44</td>
        <td class = "orderDate">12-02-2019 15:53:45.130</td>
     </tr>
     <tr></tr>
  </tbody>
   </table>
</div>

И используя приведенную ниже функцию JQuery для фильтрации записей на основе текста столбца, но не в состоянии фильтровать записи на основе имени магазина:

<script>
function testFilter(){
$(".filter").change(function() {
    var filterValue = $(this).val();
    var row = $('.record'); 
      console.info(filterValue);
    row.hide()
    row.each(function(i, el) {
         if ($(el).children().innerHTML == filterValue) {
             $(el).show();
         }
    })   
});
}
</script>
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
0
0
44
3
Перейти к ответу Данный вопрос помечен как решенный

Ответы 3

Некоторые изменения в вашем коде.

Чтобы сделать ваш фильтр лучше, вам нужно сохранить значения select ddl такими же, как значения таблицы (.store).

United Kingdom != united_kingdom

function testFilter(obj) { 

// removed .change because this method is already invoking on onchange

  var filterValue = $(obj).val(); 
  var row = $('.record');
  console.info(filterValue);
  row.hide()
  row.each(function(i, el) {

    if (

    $(el).text().toUpperCase().indexOf(filterValue.toUpperCase()) > -1 

    // used .text(), because .innerHTML will return nodes as well
    // whole content can't be same, so checked index of selected filter word
    // You can add .find('.store') if you want to make search in only store column
    // .toUpperCase() will maintain accuracy for sentence case. cause 'denmark' == 'Denmark' will return false
      ) {
      $(el).show();
    }
  })

}

function testFilter(obj) { // removed .change because this method is already invoking on onchange
  var filterValue = $(obj).val(); 
  var row = $('.record');
  console.info(filterValue);
  row.hide()
  row.each(function(i, el) {
    // used .text(), because .innerHTML will return nodes as well
    if (
$(el).text().toUpperCase().indexOf(filterValue.toUpperCase()) > -1 // whole content can't be same, so checked index of selected filter word
) {
      $(el).show();
    }
  })

}
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class = "search-button">
  <label for = "filter">Store Name:</label>
  <select class = "filter" data-tableId = "table1" onchange = "testFilter(this)">
    <option value = "all">All Stores</option>
    <option value = "United Kingdom">United Kingdom</option>
    <option value = "United States">United States</option>
    <option value = "France">France</option>
    <option value = "Denmark">Denmark</option>
    <option value = "Ireland">Ireland</option>
  </select>
</div>

<div id = "recordContent">
  <table id = "orderTable">
    <tbody>
      <tr>
        <th>Store Name</th>
        <th>Language Code</th>
        <th>Testcase Name</th>
        <th>Order Id</th>
        <th>Order Total</th>
        <th>Order Date</th>
      </tr>
      <tr class = "record">
        <td class = "store">ireland</td>
        <td class = "langCode">en_IE</td>
        <td class = "tcName">Guest User Checkout - Credit Card</td>
        <td class = "orderID">4001820209</td>
        <td class = "orderTotal">19.98</td>
        <td class = "orderDate">12-02-2019 15:37:30.201</td>
      </tr>
      <tr></tr>
      <tr class = "record">
        <td class = "store">denmark</td>
        <td class = "langCode">en_DK</td>
        <td class = "tcName">Guest User Checkout - Credit Card</td>
        <td class = "orderID">6001825084</td>
        <td class = "orderTotal">338 DKK</td>
        <td class = "orderDate">12-02-2019 15:37:35.140</td>
      </tr>
      <tr></tr>
      <tr class = "record">
        <td class = "store">united_kingdom</td>
        <td class = "langCode">en_GB</td>
        <td class = "tcName">Guest User Checkout - Credit Card</td>
        <td class = "orderID">7002541022</td>
        <td class = "orderTotal">13.04</td>
        <td class = "orderDate">12-02-2019 15:45:08.038</td>
      </tr>
      <tr></tr>
      <tr class = "record">
        <td class = "store">united_states</td>
        <td class = "langCode">en_US</td>
        <td class = "tcName">Guest User Checkout - Credit Card</td>
        <td class = "orderID">2001741036</td>
        <td class = "orderTotal">69.90</td>
        <td class = "orderDate">12-02-2019 15:46:33.310</td>
      </tr>
      <tr></tr>
      <tr class = "record">
        <td class = "store">united_kingdom</td>
        <td class = "langCode">en_GB</td>
        <td class = "tcName">Registered User Checkout - Paypal</td>
        <td class = "orderID">7002541028</td>
        <td class = "orderTotal">8.14</td>
        <td class = "orderDate">12-02-2019 15:50:04.713</td>
      </tr>
      <tr></tr>
      <tr class = "record">
        <td class = "store">united_states</td>
        <td class = "langCode">en_US</td>
        <td class = "tcName">Registered User Checkout - Paypal</td>
        <td class = "orderID">2001741030</td>
        <td class = "orderTotal">15.98</td>
        <td class = "orderDate">12-02-2019 15:51:23.551</td>
      </tr>
      <tr></tr>
      <tr class = "record">
        <td class = "store">france</td>
        <td class = "langCode">en_FR</td>
        <td class = "tcName">Guest User Checkout - Credit Card</td>
        <td class = "orderID">11002001160</td>
        <td class = "orderTotal">35.44</td>
        <td class = "orderDate">12-02-2019 15:53:45.130</td>
      </tr>
      <tr></tr>
    </tbody>
  </table>
</div>

подчеркивание против пробелов

epascarello 12.02.2019 14:57

@epascarello Да, я понимаю, но забыл упомянуть об этом. в любом случае обновил мой ответ, спасибо, что напомнили.

Abhishek Pandey 12.02.2019 14:58
Ответ принят как подходящий

Это связано с тем, что значения параметров в select не соответствуют полям в таблице. Я сделал несколько улучшений в вашем коде js:

  // I removed onchange property of your select 
  // because change event is already attached in this code
  $(".filter").change(function() {
      var translatedFilterValue = getTranslatedFilterValue($(this).val());
      var rows = $('.record'); 

      rows.each(function(i, el) {
           if (translatedFilterValue == 'all' || ($(el).find('.store').text() == translatedFilterValue)) {
               $(el).show();
           } else {
               $(el).hide();
           }
      })   
  });

  //
  // Translates text from select to corresponding values in table
  // for example: from "United States" to "united_states"
  //
  function getTranslatedFilterValue(filterValue) {
    filterValue = filterValue.toLowerCase();

    return filterValue.replace(' ', '_');
  }

Рабочая рабочий пример: НАЖМИТЕ!

зачем выполнять преобразование строк на каждой итерации? Делает цикл неэффективным

epascarello 12.02.2019 14:58

@epascarello, ты совершенно прав! Я обновил свой ответ и скрипку. Спасибо :)

aslawin 12.02.2019 15:07

$(el).children().innerHTML ищет весь текст для всей строки. Это НЕ будет соответствовать вашей строке. Другие значения выпуска имеют заглавные буквы, значения в таблице — нет. Подчеркивание есть, а значений нет.

Вы не должны иметь встроенное событие onchange, а затем привязывать onchange к этому элементу с помощью jQuery внутри него.

Код комментируется.

$(".filter").change(function() {
  var filterValue = $(this)
    .val()  // get the value of the select
      .toLowerCase()  // normalize it
        .replace(/\s/g,'_');  // replace the spaces
  var rows = $('.record');  // grab all the rows
  rows.show();  // show them
  if (filterValue !== 'all') {  // if we have all, than skip this
    rows
      .find("td.store")  // find the store tds
        .filter(function() {  // loop over read the text and see if it does not match the filter value
          return this.textContent.toLowerCase().trim() !== filterValue
        })
          .parent()  // find the trs
            .hide()  // hide the table rows that do not match
  }
});
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class = "search-button">
  <label for = "filter">Store Name:</label>
  <select class = "filter" data-tableId = "table1">
    <option value = "all">All Stores</option>
    <option value = "United Kingdom">United Kingdom</option>
    <option value = "United States">United States</option>
    <option value = "France">France</option>
    <option value = "Denmark">Denmark</option>
    <option value = "Ireland">Ireland</option>
  </select>
</div>

<div id = "recordContent">
  <table id = "orderTable">
    <tbody>
      <tr>
        <th>Store Name</th>
        <th>Language Code</th>
        <th>Testcase Name</th>
        <th>Order Id</th>
        <th>Order Total</th>
        <th>Order Date</th>
      </tr>
      <tr class = "record">
        <td class = "store">ireland</td>
        <td class = "langCode">en_IE</td>
        <td class = "tcName">Guest User Checkout - Credit Card</td>
        <td class = "orderID">4001820209</td>
        <td class = "orderTotal">19.98</td>
        <td class = "orderDate">12-02-2019 15:37:30.201</td>
      </tr>
      <tr></tr>
      <tr class = "record">
        <td class = "store">denmark</td>
        <td class = "langCode">en_DK</td>
        <td class = "tcName">Guest User Checkout - Credit Card</td>
        <td class = "orderID">6001825084</td>
        <td class = "orderTotal">338 DKK</td>
        <td class = "orderDate">12-02-2019 15:37:35.140</td>
      </tr>
      <tr></tr>
      <tr class = "record">
        <td class = "store">united_kingdom</td>
        <td class = "langCode">en_GB</td>
        <td class = "tcName">Guest User Checkout - Credit Card</td>
        <td class = "orderID">7002541022</td>
        <td class = "orderTotal">13.04</td>
        <td class = "orderDate">12-02-2019 15:45:08.038</td>
      </tr>
      <tr></tr>
      <tr class = "record">
        <td class = "store">united_states</td>
        <td class = "langCode">en_US</td>
        <td class = "tcName">Guest User Checkout - Credit Card</td>
        <td class = "orderID">2001741036</td>
        <td class = "orderTotal">69.90</td>
        <td class = "orderDate">12-02-2019 15:46:33.310</td>
      </tr>
      <tr></tr>
      <tr class = "record">
        <td class = "store">united_kingdom</td>
        <td class = "langCode">en_GB</td>
        <td class = "tcName">Registered User Checkout - Paypal</td>
        <td class = "orderID">7002541028</td>
        <td class = "orderTotal">8.14</td>
        <td class = "orderDate">12-02-2019 15:50:04.713</td>
      </tr>
      <tr></tr>
      <tr class = "record">
        <td class = "store">united_states</td>
        <td class = "langCode">en_US</td>
        <td class = "tcName">Registered User Checkout - Paypal</td>
        <td class = "orderID">2001741030</td>
        <td class = "orderTotal">15.98</td>
        <td class = "orderDate">12-02-2019 15:51:23.551</td>
      </tr>
      <tr></tr>
      <tr class = "record">
        <td class = "store">france</td>
        <td class = "langCode">en_FR</td>
        <td class = "tcName">Guest User Checkout - Credit Card</td>
        <td class = "orderID">11002001160</td>
        <td class = "orderTotal">35.44</td>
        <td class = "orderDate">12-02-2019 15:53:45.130</td>
      </tr>
      <tr></tr>
    </tbody>
  </table>
</div>

Другие вопросы по теме