Javascript: Как искать более двух столбцов в таблице - PullRequest
0 голосов
/ 23 апреля 2020

Я создаю таблицу с 4 столбцами, которые должны быть доступны для поиска. Я обнаружил, что, добавив единицу (1) в следующую строку, позвольте мне искать первые два столбца с именами «Название объекта» и «Основной номер телефона», но я не могу понять, как получить два других столбца для поиска. Я буду признателен за любую помощь, спасибо!

 td = tr[i].getElementsByTagName("td")[0,**1**];

function locations() {
  // Declare variables
  var input, filter, table, tr, td, i, txtValue;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");

  // Loop through all table rows, and hide those who don't match the search query
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[0, 1];
    if (td) {
      txtValue = td.textContent || td.innerText;
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}
#myInput {
  background-image: url('/css/searchicon.png');
  /* Add a search icon to input */
  background-position: 10px 12px;
  /* Position the search icon */
  background-repeat: no-repeat;
  /* Do not repeat the icon image */
  width: 100%;
  /* Full-width */
  font-size: 16px;
  /* Increase font-size */
  padding: 12px 20px 12px 40px;
  /* Add some padding */
  border: 1px solid #ddd;
  /* Add a grey border */
  margin-bottom: 12px;
  /* Add some space below the input */
}

#myTable {
  border-collapse: collapse;
  /* Collapse borders */
  width: 100%;
  /* Full-width */
  border: 1px solid #ddd;
  /* Add a grey border */
  font-size: 18px;
  /* Increase font-size */
}

#myTable th,
#myTable td {
  text-align: left;
  /* Left-align text */
  padding: 12px;
  /* Add padding */
}

#myTable tr {
  /* Add a bottom border to all table rows */
  border-bottom: 1px solid #ddd;
}

#myTable tr.header,
#myTable tr:hover {
  /* Add a grey background color to the table header and on hover */
  background-color: #f1f1f1;
}
<input type="text" id="myInput" onkeyup="locations()" placeholder="Search for names..">

<table id="myTable">
  <tr class="header">
    <th style="width:40%;">Facility Name</th>
    <th style="width:30%;">Main Phone Number</th>
    <th style="width:40%;">Address</th>
    <th style="width:20%;">Contract Type</th>
  </tr>
  <tr>
    <td> testing company A </td>
    <td> 855.555.5555 </td>
    <td>500 test street </td>
    <td> MSP </td>
  </tr>
  <tr>
    <td> testing company B </td>
    <td> 855.555.6666</td>
    <td> 700 test street</td>
    <td> WaaS</td>
  </tr>


</table>

Ответы [ 2 ]

1 голос
/ 23 апреля 2020

Я бы

  1. использовал eventlistener
  2. сопоставить строки с ячейкой, имеющей текст
  3. , чтобы убедиться, что HTML был действительным

window.addEventListener("load", () => {
  const table = document.querySelector("#myTable tbody");
  document.getElementById("myInput").addEventListener("input", function() {
    const input = this.value.trim();
    filter = input.toUpperCase();
    // use === 0 instead of >-1 if you want the words to start with filter
    const trs = [...table.querySelectorAll("td")].map(cell => {
      if (cell.innerText.toUpperCase().indexOf(filter) > -1) {
        return cell.closest("tr");
      }
    });
    [...table.querySelectorAll("tr")].forEach(function(tr) {
      tr.style.display = input === "" || trs.includes(tr) ? "" : "none"
    })
  })
})
#myInput {
  background-image: url('/css/searchicon.png');
  /* Add a search icon to input */
  background-position: 10px 12px;
  /* Position the search icon */
  background-repeat: no-repeat;
  /* Do not repeat the icon image */
  width: 100%;
  /* Full-width */
  font-size: 16px;
  /* Increase font-size */
  padding: 12px 20px 12px 40px;
  /* Add some padding */
  border: 1px solid #ddd;
  /* Add a grey border */
  margin-bottom: 12px;
  /* Add some space below the input */
}

#myTable {
  border-collapse: collapse;
  /* Collapse borders */
  width: 100%;
  /* Full-width */
  border: 1px solid #ddd;
  /* Add a grey border */
  font-size: 18px;
  /* Increase font-size */
}

#myTable th,
#myTable td {
  text-align: left;
  /* Left-align text */
  padding: 12px;
  /* Add padding */
}

#myTable tr {
  /* Add a bottom border to all table rows */
  border-bottom: 1px solid #ddd;
}

#myTable tr.header,
#myTable tr:hover {
  /* Add a grey background color to the table header and on hover */
  background-color: #f1f1f1;
}
<input type="text" id="myInput" placeholder="Search for names..">

<table id="myTable">
  <thead>
    <tr class="header">
      <th style="width:40%;">Facility Name</th>
      <th style="width:30%;">Main Phone Number</th>
      <th style="width:40%;">Address</th>
      <th style="width:20%;">Contract Type</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td> testing company A </td>
      <td> 855.555.5555 </td>
      <td>500 test street </td>
      <td> MSP </td>
    </tr>
    <tr>
      <td> testing company B </td>
      <td> 855.555.6666</td>
      <td> 700 test street</td>
      <td> WaaS</td>
    </tr>
  </tbody>

</table>
0 голосов
/ 23 апреля 2020

U может проверять строки без заголовка один, а затем фильтровать их

function locations() {
  // Declare variables
  var input, filter, table, tr, td, i, txtValue;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = document.querySelectorAll('tr:not(.header)');
  
  tr.forEach(x=>{
    x.style.display = 'none';
    var values=x.querySelectorAll("td");
    values.forEach(function(a){
        if ( a.innerText.toUpperCase().indexOf(filter)>-1) {
                 x.style.display = "table-row";
        }        
    });
  })
  // Loop through all table rows, and hide those who don't match the search query
}
#myInput {
  background-image: url('/css/searchicon.png');
  /* Add a search icon to input */
  background-position: 10px 12px;
  /* Position the search icon */
  background-repeat: no-repeat;
  /* Do not repeat the icon image */
  width: 100%;
  /* Full-width */
  font-size: 16px;
  /* Increase font-size */
  padding: 12px 20px 12px 40px;
  /* Add some padding */
  border: 1px solid #ddd;
  /* Add a grey border */
  margin-bottom: 12px;
  /* Add some space below the input */
}

#myTable {
  border-collapse: collapse;
  /* Collapse borders */
  width: 100%;
  /* Full-width */
  border: 1px solid #ddd;
  /* Add a grey border */
  font-size: 18px;
  /* Increase font-size */
}

#myTable th,
#myTable td {
  text-align: left;
  /* Left-align text */
  padding: 12px;
  /* Add padding */
}

#myTable tr {
  /* Add a bottom border to all table rows */
  border-bottom: 1px solid #ddd;
}

#myTable tr.header,
#myTable tr:hover {
  /* Add a grey background color to the table header and on hover */
  background-color: #f1f1f1;
}
<input type="text" id="myInput" onkeyup="locations()" placeholder="Search for names..">

<table id="myTable">
  <tr class="header">
    <th style="width:40%;">Facility Name</th>
    <th style="width:30%;">Main Phone Number</th>
    <th style="width:40%;">Address</th>
    <th style="width:20%;">Contract Type</th>
  </tr>
  <tr >
    <td> testing company A </td>
    <td> 855.555.5555 </td>
    <td>500 test street </td>
    <td> MSP </td>
  </tr>
  <tr >
    <td> testing company B </td>
    <td> 855.555.6666</td>
    <td> 700 test street</td>
    <td> WaaS</td>
  </tr>


</table>
...