Refine the inventory by using data-price attributes to narrow down the product selection

While I have successfully implemented the filtering of the product list based on store and brand in my code, I am facing challenges in filtering it with price range.

<div id="prod">
    <div class="content" data-brand="Andrew" data-price="1000" data-store="JCPenny">Andrew</div><br />
    <div class="content" data-brand="Hill" data-price="4300" data-store="JCPenny">Hill</div><br />
    <div class="content" data-brand="Andrew" data-price="1600" data-store="JCPenny">Andrew</div><br />
    <div class="content" data-brand="Hill" data-price="800" data-store="SuperMart">Hill</div><br />
    <div class="content" data-brand="Hill" data-price="2300" data-store="SuperMart">Hill</div><br />
    <div class="content" data-brand="Andrew" data-price="800" data-store="JCPenny">Andrew</div><br />
    <input type="checkbox" class="brand" id="Andrew" />Andrew
    <input type="checkbox" class="brand" id="Hill" />Hill
    <input type="checkbox" class="store" id="JCPenny" />JCPenny
    <input type="checkbox" class="store" id="SuperMart" />SuperMart
    <input type="radio" name="range" class="price" id="0-ALL"/>All
    <input type="radio" name="range" class="price" id="0-2000"/>Rs.0-2000
    <input type="radio" name="range" class="price" id="2000-4000"/>Rs.2000-4000
    <input type="radio" name="range" class="price" id="4000-6000"/>Rs.4000-6000
    <input type="radio" name="range" class="price" id=">6000"/>Rs.>6000
</div>

Above is the layout of my div. Here, I am outlining the JavaScript code for the filtering logic which has been implemented for brand and store with the assistance of my friend.

<script>
var a=$("input.brand");
var b=$("input.store");
var brand=new Array();
var store=new Array();
$("input[name=range]").change(function (e) {

alert("range");
    var toggle = this.checked;
    var range = this.value.split('-');
    var rangeFrom = parseInt(range[0]);
    var rangeTo = parseInt(range[1]);
    $(".container >div[data-price]").each(function(){
        var $this = $(this);
        // Check if category is active
        var categoryActive = $("#" + $this.data("brand")).prop("checked");
        // Get price as number
        var price = parseFloat($this.data('price'));
        // Toggle visibility based on category and price range
        $this.toggle(price >= rangeFrom && price <= rangeTo && categoryActive );
    });
});
$('input[type="checkbox"]').change(function(){
    if($(this).is(":checked")){
        $('#prod >div').hide();
        if(this.className == "brand"){
            console.debug("brand checked");
            brand.push($(this).attr('id'));
        }else if(this.className == "store"){
            console.debug("store checked");
            store.push($(this).attr('id'));
        }
        console.log(brand+","+store);
        displaydivs(brand,store);
    }else{
        $('#prod >div').show();
        if(this.className == "brand"){
            var index = brand.indexOf($(this).attr('id'));
            if (index > -1) {
                brand.splice(index, 1);
            }       
        }else if(this.className == "store"){
            var index = store.indexOf($(this).attr('id'));
            if (index > -1) {
                store.splice(index, 1);
            } 
        }
        displaydivs(brand,store);
    }     
});


function displaydivs(brand,store)
{
    $("#prod >div").hide();
    if(brand.length > 0 & store.length > 0){ 
        $.each(brand, function( index, value ){
            var temp = $("#prod >div[data-brand="+value+"]")[0];
            var data = $(temp).attr("data-store");
            var idx = store.indexOf(data);
            if(idx > -1){
              $("#prod >div[data-brand="+value+"][data-store="+data+"]").show();
          }            
      });  
        $.each(store, function( index, value ){
            var temp = $("#prod >div[data-store="+value+"]")[0];
            var data = $(temp).attr("data-brand");
            var idx = brand.indexOf(data);
            if(idx > -1){
              $("#prod >div[data-brand="+data+"][data-store="+value+"]").show();
          }            
      });
    }
    else if(brand.length > 0 & !(store.length > 0)){ 
        $.each( brand, function( index, value ){
            $("#prod >div[data-brand="+value+"]").show();
        });
    }
    else if(!(brand.length > 0) & store.length > 0){ 
        $.each( store, function( index, value ){
            $("#prod >div[data-store="+value+"]").show();
        });
    }else{
        $("#prod >div").show();
    }
}
</script>

Although the code works effectively for store and brand filters, I am now seeking assistance on implementing price range filtering. My specific requirement is as follows:

Upon selecting a brand (e.g., Andrew) and a store (e.g., JCPenny) from the checkbox list, only the divs containing both data-brand=andrew and data-store=JCPenny should be displayed. Furthermore, upon selecting a price range filter (e.g., 2000-4000), only those divs with data-brand Andrew, data-store JCPenny, and price within the specified range should be shown.

I kindly request guidance on how to enable price filtering on this product list. Any assistance would be greatly appreciated.

Answer №1

Opt for .data('store') rather than using .attr('data-store')

consistently apply this approach to all data attributes

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Identifying an Incorrect Function Call in a TypeScript Function from a JavaScript File [TypeScript, Vue.js, JavaScript]

I have a vue2 application and I am looking to incorporate TypeScript into some service files without modifying the existing js/vue files. To enable TypeScript support, I utilized vue-cli which allowed me to successfully add a myService.ts file containing ...

Making use of CSS to manipulate the placement of images within a grid

I've been struggling to insert an image into a grid, and it's causing some issues for me. Currently, the main problem I'm facing is that it's pushing another grid item down. body { padding: 0; margin: 0; } .main { wi ...

What could be preventing the background color from changing when attempting to use style.backgroundColor?

My objective is to store the current tab background color in a variable and then use that variable to change the body color. However, for some reason it is not working as expected. Can you help me figure out why? const tabName = 'someId'; var ...

Require assistance with refreshing the index for the chosen row

I have encountered a problem while attempting to manipulate table rows using Javascript. Adding new rows works fine, but deleting rows presents an issue. Specifically, the delete function fails if the first row or a row in the middle is deleted (the live ...

Utilizing jQuery DataTable with an AJAX call to retrieve data from a JSON

I am facing an issue while trying to retrieve data from Entity Framework in ASP.NET MVC using a jQuery data table with AJAX. The data is not displaying in the table as expected. I need assistance in identifying the mistake in my approach. Upon executing t ...

Verify if there are DOM elements located within a DIV container, execute the functions associated with those elements sequentially

I am in the process of creating a game using HTML, CSS, and JavaScript. My focus right now is on manipulating DOM elements without relying on the canvas tag. The goal is to develop a pseudo graphical programming language, similar to the environment provide ...

What is the integration of Google URL format with a PHP application?

When it comes to php websites, URLs are commonly written in the form of page.php?id=123 or rewrite moded page/Id/123 However, when looking at google I observed that URLs look more like google.com/search?q=Wordpress I attempted to structure website links ...

Issue encountered when trying to remove an event while a dialog is closed in a React useEffect

While working with my open dialog, I attempted to include a 'key-down' event. Unfortunately, the event continues to trigger even after the dialog is closed. To address this issue, I encapsulated the event handling function within the useEffect h ...

Error: Collision detection in Three.js console output

I am attempting to create a collision detection system using Three.js (a WEBGL library). However, I keep encountering an error stating "cannot call method multiplyVector3 of undefined". Is there anyone who can help me identify what I may be doing incorrec ...

Utilize the entire width for header elements

I have implemented four header elements: home, about, portfolio, and contact. I want these elements to stretch across the entire navigation bar with each taking up 25% of the space. How can I achieve this? Additionally, I specified that the home element sh ...

What is the reason behind HTML5Boilerplate and other frameworks opting for a CDN to host their jQuery files

When it comes to loading jQuery, HTML5Boilerplate and other sources[citation needed] have a standard process that many are familiar with: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script>window. ...

Leveraging the $dirty property in AngularJS to determine if any changes have been made to a form

Recently, I've been attempting to determine if my form is being edited by monitoring certain fields. I've come across $dirty as a potential solution for this task, but unfortunately, I'm struggling to identify what exactly I'm overlooki ...

How to use jQuery to dynamically identify the current div on a page when scrolling, even with an unpredictable number of divs

I have a container with multiple A4 pages (number varies) and I am trying to determine the current page being viewed. Below is my code: <div class="mycont"> <div id="page1" style="width: 21cm; height:29.7cm; border: ...

Having trouble integrating select2 with geonames?

I'm currently experiencing difficulties when trying to integrate select2 with geonames. Although I am able to generate a list of cities, I am unable to select any as a valid option. HTML <select id="cities" name= "cities"> <option value=" ...

Utilize $.get AJAX to extract data from a multidimensional JSON array

Struggling to make two functions work on my form that uses AJAX and jQuery to look up an array. One function is functional while the other seems to be causing confusion with over-analysis and extensive troubleshooting. Any insights into what may be missing ...

Using NodeJS to perform asynchronous tasks with setImmediate while also incorporating private class

Today marks my first time experimenting with setImmediate. I've come to realize that it may not be able to run private class methods. Can someone shed some light on this? Why is that the case? Not Functioning Properly When trying to use a private cl ...

How can you prevent a draggable element from surpassing the bottom of the screen?

I'm dealing with an element that I want to make draggable only along the Y-axis. It needs to be able to go past the top of the screen, but I need to restrict it from going past the bottom of the screen. I recently came across the containment feature i ...

How to target a class with a specific number in CSS selectors

My mobile hybrid application is built with Sencha Touch 2 and requires some customization based on the iOS version it's running on. In my Sass stylesheet, I originally had the following selector: .x-ios-7 { /* add iOS7 customizations here */ } How ...

Why is Django not recognizing my ajax request when using the `is_ajax()` function?

After sending a GET request and processing the data to obtain a redirect link, the function seems to be having trouble entering the is_ajax() block. $(document).on('click', '.top_up_pay', function (e) { var post_data; e.preventDefa ...

What strategies do developers use to manage front-end dependencies in projects that are not part of any specific

Although I am well-versed in using NPM for front-end projects, I am interested in understanding how others manage front-end dependencies for non-application based "brochure-site" projects. For instance, if I am working on a WordPress theme and need to inc ...