Product Filter and Search Using JavaScript

Product Filter and Search Using JavaScript
Code Snippet:Product Search / Filter
Author: Ir
Published: 1 month ago
Last Updated: June 14, 2024
Downloads: 99
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript code snippet helps you to create a dynamic product filter and search functionality on webpage. It generates product cards from an array of product data. The products can be filtered by make, model, and type through dropdown menus. Additionally, users can search for products by entering keywords. This helps in quickly finding specific products in a large dataset.

You can use this code on an e-commerce website to allow users to filter and search for products. One benefit is that it improves the user experience by making it easier to find specific items quickly.

How to Create Product Filter and Search Using JavaScript

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

<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css'>

2. After that, create a basic HTML structure that includes placeholders for product display, filter dropdowns, and a search form.

<div class="container">
	<div class="row" id="search">
		<form id="search-form" action="" method="POST" enctype="multipart/form-data">
			<div class="form-group col-xs-9">
				<input class="form-control" type="text" placeholder="Search" />
			</div>
			<div class="form-group col-xs-3">
				<button type="submit" class="btn btn-block btn-primary">Search</button>
			</div>
		</form>
	</div>
	<div class="row" id="filter">
		<form>
			<div class="form-group col-sm-3 col-xs-6">
				<select data-filter="make" class="filter-make filter form-control">
					<option value="">Select Make</option>
					<option value="">Show All</option>
				</select>
			</div>
			<div class="form-group col-sm-3 col-xs-6">
				<select data-filter="model" class="filter-model filter form-control">
					<option value="">Select Model</option>
					<option value="">Show All</option>
				</select>
			</div>
			<div class="form-group col-sm-3 col-xs-6">
				<select data-filter="type" class="filter-type filter form-control">
					<option value="">Select Type</option>
					<option value="">Show All</option>
				</select>
			</div>
			<div class="form-group col-sm-3 col-xs-6">
				<select data-filter="price" class="filter-price filter form-control">
					<option value="">Select Price Range</option>
					<option value="">Show All</option>
				</select>
			</div>
		</form>
	</div>
	<div class="row" id="products">
		
	</div>
</div>

3. In your styles.css file, customize the appearance of elements to enhance visual appeal and user interaction. Style the container (.container) for layout and background, and adjust the .filters section to ensure labels and inputs are aligned neatly. Define dimensions, padding, and borders for clarity and usability.

body {
	padding-top: 30px;
}
.product {
	margin-bottom: 30px;
}
.product-inner {
	box-shadow: 0 0 10px rgba(0,0,0,.2);
	padding: 10px;
}
.product img {
	margin-bottom: 10px;
}

4. Now, load the jQuery and Bootstrap JS by adding the following CDN links just before closing the body tag:

<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js'></script>
<script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js'></script>

5. Finally, in script.js, start by defining an array (data) containing product information such as make, model, type, price, and image URLs. Initialize variables (products, makes, models, types) to store generated HTML content and dropdown options.

Use a loop to dynamically create HTML for each product card (products variable) and populate dropdown options (makes, models, types variables) without duplicates.

Update the DOM by inserting the generated HTML into respective containers (#products, .filter-make, .filter-model, .filter-type).

var data = [
	{
		"make": "Gibson",
		"model": "Les Paul",
		"type": "Electric",
		"price": "$3,000",
		"image": "http://www.sweetwater.com/images/items/120/LPST5HTHDCH-medium.jpg?9782bd"
	},
	{
		"make": "Gibson",
		"model": "SG",
		"type": "Electric",
		"price": "$1,500",
		"image": "http://www.sweetwater.com/images/items/120/SGSEBCH-medium.jpg?e69cfe"
	},
	{
		"make": "Fender",
		"model": "Telecaster",
		"type": "Electric",
		"price": "$2,000",
		"image": "http://www.sweetwater.com/images/items/120/TelePLMPHB-medium.jpg?28e48b"
	},
	{
		"make": "Fender",
		"model": "Stratocaster",
		"type": "Electric",
		"price": "$2,000",
		"image": "http://www.sweetwater.com/images/items/120/StratAMM3SB2-medium.jpg?dfd0a9"
	},
	{
		"make": "Gretsch",
		"model": "White Falcon",
		"type": "Electric",
		"price": "$5,000",
		"image": "http://www.sweetwater.com/images/items/120/G613655GE-medium.jpg?9bfb0e"
	},
	{
		"make": "Paul Reed Smith",
		"model": "Custom 24",
		"type": "Electric",
		"price": "$5,000",
		"image": "http://www.sweetwater.com/images/items/120/HBII10BGWB-medium.jpg?982763"
	},
	{
		"make": "Gibson",
		"model": "Hummingbird",
		"type": "Acoustic",
		"price": "$2,500",
		"image": "http://www.sweetwater.com/images/items/120/SSHBHCNP-medium.jpg?11fbea"
	}
];

var products = "",
	makes = "",
	models = "",
	types = "";

for (var i = 0; i < data.length; i++) {
	var make = data[i].make,
		model = data[i].model,
		type = data[i].type,
		price = data[i].price,
		rawPrice = price.replace("$",""),
		rawPrice = parseInt(rawPrice.replace(",","")),
		image = data[i].image;
	
	//create product cards
	products += "<div class='col-sm-4 product' data-make='" + make + "' data-model='" + model + "' data-type='" + type + "' data-price='" + rawPrice + "'><div class='product-inner text-center'><img src='" + image + "'><br />Make: " + make + "<br />Model: " + model + "<br />Type: " + type + "<br />Price: " + price + "</div></div>";
	
	//create dropdown of makes
	if (makes.indexOf("<option value='" + make + "'>" + make + "</option>") == -1) {
		makes += "<option value='" + make + "'>" + make + "</option>";
	}
	
	//create dropdown of models
	if (models.indexOf("<option value='" + model+"'>" + model + "</option>") == -1) {
		models += "<option value='" + model + "'>" + model + "</option>";
	}
	
	//create dropdown of types
	if (types.indexOf("<option value='" + type + "'>" + type + "</option>") == -1) {
		types += "<option value='" + type + "'>" + type + "</option>";
	}
}

$("#products").html(products);
$(".filter-make").append(makes);
$(".filter-model").append(models);
$(".filter-type").append(types);

var filtersObject = {};

//on filter change
$(".filter").on("change",function() {
	var filterName = $(this).data("filter"),
		filterVal = $(this).val();
	
	if (filterVal == "") {
		delete filtersObject[filterName];
	} else {
		filtersObject[filterName] = filterVal;
	}
	
	var filters = "";
	
	for (var key in filtersObject) {
	  	if (filtersObject.hasOwnProperty(key)) {
			filters += "[data-"+key+"='"+filtersObject[key]+"']";
	 	}
	}
	
	if (filters == "") {
		$(".product").show();
	} else {
		$(".product").hide();
		$(".product").hide().filter(filters).show();
	}
});

//on search form submit
$("#search-form").submit(function(e) {
	e.preventDefault();
	var query = $("#search-form input").val().toLowerCase();

	$(".product").hide();
	$(".product").each(function() {
		var make = $(this).data("make").toLowerCase(),
			model = $(this).data("model").toLowerCase(),
			type = $(this).data("type").toLowerCase();

		if (make.indexOf(query) > -1 || model.indexOf(query) > -1 || type.indexOf(query) > -1) {
			$(this).show();
		}
	});
});

That’s all! hopefully, you have successfully created a product filter and search using JavaScript. 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.