This article describes the various search functions of JS to implement table data. It can ignore case, fuzzy search, and multiple key searches. Share it for your reference. The specific implementation method is as follows:
Copy the code as follows: <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
window.onload=function(){
var oTab=document.getElementById("tab");
var oBt=document.getElementsByTagName("input");
oBt[1].onclick=function(){
for(var i=0;i<oTab.tBodies[0].rows.length;i++)
{
var str1=oTab.tBodies[0].rows[i].cells[1].innerHTML.toUpperCase();
var str2=oBt[0].value.toUpperCase();
//Use string.toUpperCase() (convert all characters in the string to uppercase) or string.toLowerCase() (convert all characters in the string to lowercase)
//The so-called search for ignoring uppercase and lowercase is to convert all strings entered by the user to uppercase or lowercase, then convert all strings in the information table to uppercase or lowercase, and finally compare the converted characters of the two.
/***************************JS implements tables ignore case search************************************/
if(str1==str2){
oTab.tBodies[0].rows[i].style.background='red';
}
else{
oTab.tBodies[0].rows[i].style.background='';
}
/******************************JS implements fuzzy search of tables******************************/
//The fuzzy search of the table is to use a search() method in JS, using the format, string1.search(string2);
//The string entered by the user is a substring, which will return the position of the substring in the main string. If it does not match, it will return -1. Therefore, the operation is as follows
if(str1.search(str2)!=-1){oTab.tBodies[0].rows[i].style.background='red';}
else{oTab.tBodies[0].rows[i].style.background='';}
/*********************************JS implements multi-keyword search for tables******************************/
// Search for multiple keywords in the table. If you add multiple keywords entered by the user, use the split method to divide a long string into a string array with spaces as the standard.
// Then compare the substrings of the cut array with the strings in the information table in a loop
var arr=str2.split(' ');
for(var j=0;j<arr.length;j++)
{
if(str1.search(arr[j])!=-1){oTab.tBodies[0].rows[i].style.background='red';}
}
}
}
}
</script>
</head>
<body>
Name:<input type="text" />
<input type="button" value="Search"/>
<table bordercolor="blue" id="tab">
<head>
<td><h2>ID</h2></td>
<td><h2>Name</h2></td>
<td><h2>Age</h2></td>
</head>
<tbody>
<tr>
<td>1</td>
<td>Blue</td>
<td>15</td>
</tr>
<tr>
<td>2</td>
<td>Mikyou</td>
<td>26</td>
</tr>
<tr>
<td>3</td>
<td>weak</td>
<td>24</td>
</tr>
<tr>
<td>4</td>
<td>sky</td>
<td>35</td>
</tr>
<tr>
<td>5</td>
<td>Li Si</td>
<td>18</td>
</tr>
</tbody>
</table>
</body>
</html>
I hope this article will be helpful to everyone's JavaScript programming.