I have an HTML table that uses the rowspan attribute. I’ve added a search feature to the table, but when I search for something like "Washington," it removes the values "Monkey" and "Lion" from the ABC column and replaces them with values from the DEF column. I’m not sure how to fix this. Do you have any advice? Here is my code –
function searchTable() {
var input, filter, table, tr, td, i, j, txtValue, match;
input = document.getElementById("searchInput");
filter = input.value.toUpperCase();
table = document.getElementById("example_full");
tr = table.getElementsByTagName("tr");
match = false;
for (i = 1; i < tr.length; i++) { // Skip the header row
tr[i].style.display = "none"; // Hide all rows initially
td = tr[i].getElementsByTagName("td");
for (j = 0; j < td.length; j++) {
if (td[j]) {
txtValue = td[j].textContent || td[j].innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
match = true;
break;
}
}
}
}
// Show or hide the no match message
document.getElementById("noMatch").style.display = match ? "none" : "block";
}
.no-match {
display : none;
color : red;
}
th {
border-left : 1px solid #dddddd;
border-top : 1px solid #dddddd;
border-bottom : 1px solid #dddddd;
border-right : 1px solid #dddddd;
background-color: darkgray;
}
<input type="text" id="searchInput" placeholder="Search for records..." onkeyup="searchTable()" />
<p id="noMatch" class="no-match">No matching records found</p>
<table id="example_full">
<thead>
<tr>
<th>ABC</th>
<th>DEF</th>
<th>GHI</th>
<th>XXX</th>
<th>MMM</th>
</tr>
</thead>
<tbody>
<tr>
<td rowspan="4" style=" vertical-align: middle;">MONKEY</td>
<td>AD123</td>
<td>434SDD</td>
<td>DFDDFF</td>
<td>FDFFD</td>
</tr>
<tr>
<td>LEMON</td>
<td> </td>
<td>FDFGGF</td>
<td>DFFDF</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td>FDDFF</td>
<td>Edison</td>
</tr>
<tr>
<td>FDDFFDF</td>
<td> </td>
<td>East</td>
<td>Washington</td>
</tr>
<tr>
<td rowspan="3" style=" background-color: #F9F9F9; vertical-align: middle;">LION</td>
<td>GFFG</td>
<td>FGFGG</td>
<td>FGFG</td>
<td>FGGFGFG</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td>FGHGH</td>
<td>DDDFF</td>
</tr>
<tr>
<td></td>
<td>test2</td>
<td>FFGGFH</td>
<td>Washington</td>
</tr>
</tbody>
</table>
3
Answers
Make sure each row has 5 cells. In your case you collapse to 4 cells on rows that do not have the rowspan
Here is a more streamlined version using imhvost’s suggestion to collapse the visibility instead of display:none/hidden
Use
tr { visibility: collapse; }
instead oftr { display: none; }
:Per your comment ‘Is there a way to still show the value for column ABC if I search "Lemon", here is a solution that will create and delete cells and labels as needed. I tried to add some basic comments to the js code to help explain what is going on.