Live Search using JavaScript

A live search is an enhanced search form that uses javascript technology to deliver results or suggestions within the same view. This is different from a regular HTML input field that is given autocomplete powers from a modern browser like Chrome, Firefox or Safari. A live search is often an input field that has been programmed to load suggestions from a specific dataset.

Using live search in your application greatly improves the user friendliness of your site. Whatever back-end technology you are using — PHP, Java, Python, Ruby — JavaScript is your best bet in implementing a client-side live search feature.

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Live Search</title>
<style>
* {
box-sizing: border-box;
}

#myInput {
background-image: url('/css/searchicon.png');
background-position: 10px 10px;
background-repeat: no-repeat;
width: 100%;
font-size: 16px;
padding: 12px 20px 12px 40px;
border: 1px solid #ddd;
margin-bottom: 12px;

}

#myTable {
border-collapse: collapse;
width: 100%;
border: 1px solid #ddd;
font-size: 18px;
}

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

#myTable tr {
border-bottom: 1px solid #ddd;
}

#myTable tr.header, #myTable tr:hover {
background-color: #f1f1f1;
}
</style>
</head>
<body>

<h2>My Customers</h2>

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">

<table id="myTable">
<tr class="header">
<th style="width:60%;
background-color:orange;">State Name</th>
</tr>
<tr>
<td>Gujrat</td>
</tr>
<tr>
<td>Maharastra</td>
</tr>
<tr>
<td>Bihar</td>
</tr>
<tr>
<td>Rajasthan</td>
</tr>
<tr>
<td>Jammu & Kashmir</td>
</tr>
<tr>
<td>Panjab</td>
</tr>
<tr>
<td>Uttar Pradesh</td>
</tr>
</table>

<script>
function myFunction() {
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
} 
}
}
</script>

</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *