I have an HTML table with a search function that works well. However, my search function only finds the results based on the existing table data. I am trying to show results for terms that aren't in the table. I am able to do this but with limited success.
As an example, if I search for "Apple Banana" (text that is not part of my table), the results are the same as if I searched for "ABC" (text that is part of my table). See my table below for example.
The problem is, I only get results after searching the entire term "Apple Banana". Is there a way to search for "App" or "Ban" (not exact match but contains) and still get the results? If using an object is not the best approach, I am open to any other suggestions. Note that the HTML table is generated automatically by the Content Management System and I am not able to manipulate it. I can update JavaScript or CSS file.
const obj = {
'Apple Banana':'ABC',
};
function myFunction() {
let userInput = document.getElementById("myInput").value;
if(obj[userInput]) userInput = obj[userInput];
userInput = userInput.toUpperCase();
const tableRows = document.querySelectorAll("table tr");
for (let i = 0; i < tableRows.length; i++) {
const rowTextContent = tableRows[i].innerText.toUpperCase();
tableRows[i].style.display = rowTextContent.toUpperCase().includes(userInput) ? "" : "none";
}
}
table.table_brdr td {
padding: 8px 10px;
border: none;
}
table.table_brdr th {
background-color: #a6a6a6;
color: black;
}
tr:nth-of-type(odd) {
background-color#D3D3D3;
}
#myInput {
background-image: url('/css/searchicon.png');
background-position: 10px 10px;
background-repeat: no-repeat;
width: 20%;
font-size: 16px;
padding: 12px 20px 12px 40px;
border: 1px solid #ddd;
margin-bottom: 12px;
}
<p><input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search forms list" title="Search forms list"></p>
<table class="table_brdr" id="myTable">
<tr>
<th>Column1</th>
<th><strong>Column2</th>
<th>Column3</th>
</tr>
<tr>
<td>abc</td>
<td>xyz</td>
<td>03/30/2017</td>
</tr>
<tr>
<td>test12</td>
<td>https://www.yahoo.com/ </td>
<td>03/30/2017</td>
</tr>
<tr>
<th>Column1</th>
<th> New Column</th>
<th>Column3</th>
</tr>
<tr>
<td>John</td>
<td>abctd <td>
<td>09/30/2019</td>
</tr>
<tr>
<th>Column1</th>
<th> New Column2</th>
<th>Column3</th>
</tr>
<tr>
<td>Doe</td>
<td>abctd </td>
<td>06/30/2019</td>
</tr>
</tbody></table>
Comments
Post a Comment