Filter Table with Select Option in JavaScript

Filter Table with Select Option in JavaScript
Code Snippet:Table Filter
Author: Regina Battle
Published: January 10, 2024
Last Updated: January 22, 2024
Downloads: 1,872
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript code snippet helps you to create a table with select option filter functionality. It comes with a simple interface for filtering a table based on a user’s selection. It works by using a dropdown menu to choose an option and the table dynamically displays only the rows corresponding to the selected option.

This code is helpful for organizing and presenting data in a user-friendly manner by allowing users to filter the table based on specific criteria.

How to Create Table with Select Option Filter Functionality in JavaScript

1. First of all, load the Reset CSS by adding the following CDN link into the head tag of your HTML document. (Optional)

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">

2. Create the HTML structure for your table and the dropdown menu. The code below demonstrates a sample HTML structure:

<div class="table-filters">
	<select id="filter">
		<option disabled selected value="none">Select a genre</option>
		<option>Hip Hop</option>
		<option>Jazz</option>
		<option>Soul</option>
		<option>R&B</option>
	</select>
</div>

<table>
	<thead>
		<tr>
			<th>Album title</th>
			<th>Artist</th>
			<th>Genre</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td>Illmatic</td>
			<td>Nas</td>
			<td>Hip Hop</td>
		</tr>
		<tr>
			<td>Beyoncé</td>
			<td>Lemonade</td>
			<td>R&B</td>
		</tr>
		<tr>
			<td>Marvin Gaye</td>
			<td>Let's Get It On</td>
			<td>Soul</td>
		</tr>
		<tr>
			<td>Bitches Brew</td>
			<td>Miles Davis</td>
			<td>Jazz</td>
		</tr>
		<tr>
			<td>Channel Orange</td>
			<td>Frank Ocean</td>
			<td>R&B</td>
		</tr>
		<tr>
			<td>Midnight Marauders</td>
			<td>A Tribe Called Quest</td>
			<td>Hip Hop</td>
		</tr>
		<tr>
			<td>Oxnard</td>
			<td>Anderson Paak</td>
			<td>R&B</td>
		</tr>
		<tr>
			<td>Talking Book</td>
			<td>Stevie Wonder</td>
			<td>Soul</td>
		</tr>
		<tr>
			<td>A Love Supreme</td>
			<td>John Coltrane</td>
			<td>Jazz</td>
		</tr>
		<tr>
			<td>Lady Soul</td>
			<td>Aretha Franklin</td>
			<td>Soul</td>
		</tr>
	</tbody>
</table>

3. Apply the following CSS styles to your HTML elements to make them visually appealing. You can use the provided CSS or customize it to fit your design.

@import url("https://fonts.googleapis.com/css?family=Be+Vietnam:400,500&display=swap");
*, ::after, ::before {
  box-sizing: border-box;
}

body {
  background: #EEF9F0;
  font-family: "Be Vietnam", sans-serif;
  font-size: 16px;
  font-weight: 400;
  line-height: 1.4;
  padding: 2em;
}

.table-filters {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 2em;
}
.table-filters a {
  color: #222;
  font-size: 16px;
  font-weight: 500;
  margin-right: 1em;
  display: inline-block;
}
.table-filters a:hover {
  text-decoration: none;
}
.table-filters select {
  background: #fff;
  font-family: "Be Vietnam", sans-serif;
  font-size: 16px;
  font-weight: 500;
  width: 12em;
  height: 2.5em;
}

table {
  background: #fff;
  width: 100%;
  table-layout: fixed;
  border-radius: 6px;
}

thead {
  background: #1A5DC8;
  color: #fff;
  
}

th {
  font-size: 16px;
  font-weight: 500;
  text-align: left;
  padding: 1.5em 1em !important;
  border-bottom: 1px solid #ddd;
}

tbody td {
  padding: 1.5em 1em;
}

tbody tr.show {
  display: table-row;
}
tbody tr.hidden {
  display: none;
}
tbody tr.bg-grey, tbody tr:nth-child(odd) {
  background: #f1f1f1;
}
tbody tr:last-child td {
  border-bottom: none;
}

/* Media queries */
@media (min-width: 520px) {
  body {
    padding: 3em;
  }
}

4. Finally, add the JavaScript code to your HTML file within a <script> tag, either in the <head> or just before the closing </body> tag.

// Highlight odd rows
highlightRows = () => {
	let oddRows = document.querySelectorAll('tbody tr.show')
	oddRows.forEach((row, index)=> {
		if (index % 2 == 0) {
			row.style.background = '#f1f1f1'
		} else {
			row.style.background = '#fff'
		}
	})
}

// Filter table based on select
const filterOptions = () => {
	const option = document.querySelector("#filter").value;
	const selection = option.replace('&', '')
	const rows = document.querySelectorAll("tbody tr");
	
	rows.forEach(row => {
		let td = row.querySelector("td:last-child");
		let filter = td.innerText.replace('&', '');
		if (filter === selection) {
			row.className = 'show'
		} else {
			row.className = 'hidden'
		}
	});
	highlightRows()
};
document.getElementById("filter").addEventListener("change", filterOptions);

That’s all! hopefully, you have successfully created an HTML table with select option filter functionality on your website. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X