JQuery


Example: Filtering a Table by Key Press


	<head>
	<meta charset="UTF-8">
	<title>HTML JQuery</title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
	<script>
	$(document).ready(function(){
	  $("#myInput").on("keyup", function() {
		var value = $(this).val().toLowerCase();
		$("#myTable tr").filter(function() {
		  $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
		});
	  });
	});
	</script>
	<style>
	table {
	  font-family: arial, sans-serif;
	  border-collapse: collapse;
	  width: 100%;
	}
	td, th {
	  border: 1px solid #dddddd;
	  text-align: left;
	  padding: 8px;
	}
	th {
	  background-color: #0143ad;
	  color: white;
	}
	tr:nth-child(even) {
	  background-color: #c3d7f7;
	}
	</style>
	</head>
	<body>

	<h2>January Customers</h2>

	<p>Enter text to filter customers displayed:</p>  

	<p><input id="myInput" type="text" placeholder="Enter text..."></p>

	<table>
	  <thead>
	  <tr>
		<th>Firstname</th>
		<th>Lastname</th>
		<th>City</th>
	  </tr>
	  </thead>
	  <tbody id="myTable">
	  <tr>
		<td>Harold</td>
		<td>Patterson</td>
		<td>Southfield</td>
	  </tr>
	  <tr>
		<td>Susan</td>
		<td>Daniels</td>
		<td>Dearborn</td>
	  </tr>
	  <tr>
		<td>Sam</td>
		<td>Mohammed</td>
		<td>Dearborn Heights</td>
	  </tr>
	  <tr>
		<td>April</td>
		<td>Williams</td>
		<td>Allen Park</td>
	  </tr>
	  </tbody>
	</table>
	

The code above does the following:

  • As keys pressed on keyboard in myInput search box, examine each row of the table to check for text matches with text inputted in myInput search box by user
  • toLowerCase() converts text to lowercase so search is case insensitive
  • Table heading row is exlcuded from filtering
  • toggle() method only displays table rows that match

Run it:

jq2.html