Product Recommendation Based On Selection in JavaScript

Product Recommendation Based On Selection in JavaScript
Code Snippet:
Author: Girish kumar Dewangan
Published: January 19, 2024
Last Updated: January 22, 2024
Downloads: 337
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript code snippet helps you to create product recommendation based on user selection. It captures preferences like type, brand, and price range. The `getRecommendation` function processes these selections and displays product suggestions. It helps suggest items based on specific criteria chosen by the user.

You can use this code on websites for product recommendations. It helps users find relevant items based on their preferences, improving their shopping experience.

How to Create Product Recommendation Based On Selection in JavaScript

1. Copy the following HTML code into your project. It includes a form with dropdowns for product type and brand, a price range slider, and a “Get Recommendation” button.

<div class="container">
    <h1>Product Recommendation</h1>

    <form id="productForm" onsubmit="getRecommendation(); return false;">
        <label for="productType">Product Type:</label>
        <select id="productType">
            <option value="laptop">Laptop</option>
            <option value="phone">Phone</option>
            <option value="camera">Camera</option>
            <!-- Add more product types as needed -->
        </select>

        <label for="brandName">Brand Name:</label>
        <select id="brandName">
            <option value="apple">Apple</option>
            <option value="samsung">Samsung</option>
            <option value="sony">Sony</option>
            <!-- Add more brand names as needed -->
        </select>

        <label for="priceRange">Price Range:</label>
        <input type="range" id="priceRange" min="0" max="1000" step="50" value="500">
        <span id="priceValue">500</span>

        <button type="submit">Get Recommendation</button>
    </form>

    <div id="recommendationResult" class="result-container"></div>
</div>

2. Paste the following CSS code to make your form visually appealing. Feel free to customize the styles according to your website’s design.

body {
    font-family: 'Arial', sans-serif;
    margin: 0;
    padding: 0;
    background-color: #f5f5f5;
}

.container {
    max-width: 800px;
    margin: 50px auto;
    background-color: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

h1 {
    text-align: center;
    margin-bottom: 20px;
}

form {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    margin-bottom: 20px;
}

label {
    margin-bottom: 10px;
}

select,
input[type="range"] {
    width: calc(33.33% - 10px);
    padding: 8px;
    margin-bottom: 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
}

input[type="range"] {
    width: calc(66.66% - 10px);
    margin-bottom: 0;
}

button {
    width: 100%;
    padding: 10px;
    background-color: #4caf50;
    color: #fff;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

button:hover {
    background-color: #45a049;
}

#recommendationResult {
    margin-top: 20px;
}

.result-container {
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
}

3. Finally, add the following JavaScript code to capture user selections and generate product recommendations. The getRecommendation function retrieves values from the form, calls generateHardcodedRecommendations (replace with your logic or API call), and displays the results using displayRecommendations.

function getRecommendation() {
    // Get selected values from the form
    const productType = document.getElementById('productType').value;
    const brandName = document.getElementById('brandName').value;
    const priceRange = document.getElementById('priceRange').value;

    // Replace this with your logic or API call to get recommendations
    const recommendations = generateHardcodedRecommendations(productType, brandName, priceRange);

    // Display recommendations
    displayRecommendations(recommendations);
}

function generateHardcodedRecommendations(productType, brandName, priceRange) {
    // Replace this with your logic or API call to generate recommendations
    // For demonstration purposes, using hardcoded recommendations
    const recommendations = [
        { name: 'Product 1', type: productType, brand: brandName, price: priceRange },
        { name: 'Product 2', type: productType, brand: brandName, price: priceRange },
        { name: 'Product 3', type: productType, brand: brandName, price: priceRange }
    ];

    return recommendations;
}

function displayRecommendations(recommendations) {
    const resultContainer = document.getElementById('recommendationResult');
    resultContainer.innerHTML = '';

    if (recommendations.length === 0) {
        resultContainer.innerHTML = '<p>No recommendations found.</p>';
    } else {
        recommendations.forEach(product => {
            const productCard = document.createElement('div');
            productCard.classList.add('result-container');

            const details = document.createElement('p');
            details.innerHTML = `<strong>Name:</strong> ${product.name}<br>
                                 <strong>Type:</strong> ${product.type}<br>
                                 <strong>Brand:</strong> ${product.brand}<br>
                                 <strong>Price:</strong> ${product.price}`;

            productCard.appendChild(details);
            resultContainer.appendChild(productCard);
        });
    }
}

Replace the generateHardcodedRecommendations function with your recommendation logic or API call. This is where you can implement personalized algorithms to fetch real-time suggestions.

That’s all! hopefully, you have successfully created a Product Recommendation Based on Selection 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...