Search and Filter Table Rows

I have some code, that takes a search query, and uses that query to filter out rows in a table. So, if I type “leather” … it looks for rows that contain “leather” and hides rows that do not contain the word. The problem that I have, is that I only want to search the first column (but it searches every column in the row). Here is a codepen of the current code

(the row containing “hide” should not appear when I search for “leather” … but it does because of "leather"worker is in column 5 …)

Can someone help me fix the javascript to search only “col1” and hide all the rows that do not contain the search query (“rowx”). I do not know javascript well (at all), so please help if you can.

There is no need for all that code (or the overhead of jQuery). Try:


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Filter Table 1</title>
<style>
div{
  display: flex;
  overflow-x:auto;
}  
table{
  flex: 0 1 500px;
  border-collapse: collapse;
}
tr:first-child{
  background: #ece1ce;
}
th, td{
  text-align: right;
  border-bottom: 1px solid #e3d5bc;
  border-left: 20px;
  padding: 5px 0;
}
th:first-child, td:first-child{
  text-align: left;
  border-left: none;
}
</style>
</head>
<body>
<input type="text">
<div class="container">
  <table>
    <tbody>
      <tr>
        <th>Item</th>
        <th>Price</th>
        <th>Cost</th>
        <th>Time</th>
        <th>Tools</th>
      </tr>
      <tr>
        <td>Padded</td>
        <td>5 gp</td>
        <td>3 gp</td>
        <td>4 hours</td>
        <td>Weaver's Tools</td>
      </tr>
      <tr>
        <td>Leather</td>
        <td>10 gp</td>
        <td>5 gp</td>
        <td>8 hours</td>
        <td>Leatherworker's Tools</td>
      </tr>
      <tr>
        <td>Studded Leather</td>
        <td>45 gp</td>
        <td>23 gp</td>
        <td>5 days</td>
        <td>Leatherworker's Tools</td>
      </tr>
      <tr>
        <td>Hide</td>
        <td>10 gp</td>
        <td>5 gp</td>
        <td>8 hours</td>
        <td>Leatherworker's Tools</td>
      </tr>
      <tr>
        <td>Chain Shirt</td>
        <td>50 gp</td>
        <td>25 gp</td>
        <td>3 days</td>
        <td>Smith's Tools</td>
      </tr>
    </tbody>
  </table>
</div>
<script>
const t = document.querySelector("table");
      
function filter(){
  const v = document.querySelector("input").value.toLowerCase();
  if(v.length <3) return;  // optional parameter
  const rows = t.rows;  
  for (let z=1 ; z<rows.length ; z++)
    {
	  if(rows[z].cells[0].innerText.toLowerCase().includes(v) ) rows[z].style.display="table-row";
      else rows[z].style.display="none";
    }
}
document.querySelector("input").addEventListener("input", filter);
</script>
</body>
</html>

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.