Manipulate the visibility of div sections depending on the selected price and category checkboxes using JavaScript

I have a unique div setup where I'm defining data attributes to display a product list. Each div contains data attributes for category (data-category) and price (data-price). I want to be able to show or hide specific divs based on selections made using checkboxes for category and price. Below is the structure of the HTML:

<div class="content" data-category="shoes" data-price="1000">shoe1</div><br />
<div class="content" data-category="shirts" data-price="1200">shirt1</div><br />

<div class="content" data-category="shoes" data-price="2000">shoe2</div><br />
<div class="content" data-category="shoes" data-price="800">shoe3</div><br />
<div class="content" data-category="shirts" data-price="1300">shirt2</div><br />
<div class="content" data-category="shirts" data-price="800">shirt3</div><br />

<input type="checkbox" class="category" category="shoes" id="shoes">shoes
<input type="checkbox" class="category" category="shirts" id="shirts">shirts

Currently, I have checkboxes set up for selecting categories, but I'm struggling with implementing a range jQuery slider for selecting prices. Ideally, when a user selects a category checkbox (e.g. shoes), only the corresponding div elements should be displayed. Then, if the user applies a price filter within a specified range, only the div elements falling within that range should be displayed.

For instance: If "shoes" is selected, only shoe divs should be shown. If a price range of 1000-2000 is applied, then only shoe1 and shoe2 should be displayed, excluding shoe3. Any assistance with this would be greatly appreciated.

Answer №1

When it comes to HTML attributes, using "category" may not be the best choice. It would be more appropriate to use a different attribute name, like an ID, which is what you need in this scenario:

<input type="checkbox" class="category" id="shoes">shoes
<input type="checkbox" class="category" id="shirts">shirts

For creating ranges, consider something similar to this setup:

<input type="radio" name="range" value="0-9000" checked>All
<input type="radio" name="range" value="0-999">0-1000
<input type="radio" name="range" value="1000-2000">1000-2000

Then, in your JavaScript code:

$("input.category").prop("checked", true).change(function (e) {
    //Trigger change event on active price range item where the filter is applied
    $("input[name=range]:checked").trigger("change");
});
$("input[name=range]").change(function (e) {
    var toggle = this.checked;
    var range = this.value.split('-');
    var rangeFrom = parseInt(range[0]);
    var rangeTo = parseInt(range[1]);
    // If all category checkboxes are off we will ignore category filter
    var allOff = ($("input[type=checkbox]:checked").length === 0);
    $(".content[data-price]").each(function(){
        var $this = $(this);
        // Check if category is active
        var active = allOff || $("#" + $this.data("category")).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 && active );
    });
});

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

Having trouble centering the links in the Bootstrap navbar?

I've been struggling to center the links/tabs on my Bootstrap navbar for days now and I just can't seem to get it right. I've gone through countless similar questions without any luck. Something must be off in my code or maybe I'm not t ...

The Journey of React Native Routing

When building my React Native application, I encountered a challenge with creating a Footer and Tab menu that should only be displayed on certain screens. If I define them within the NavigationContainer, they apply to all screens uniformly. How can I sep ...

What is the process for obtaining the Tag from a React Component?

Not the HTML DOM element tag, the JSX tag, the react class name. As I work on creating an editor, adding items to the canvas array requires me to check and call the appropriate method based on what is being added. A simplified version of my idea: changeS ...

The Axios onDownloadProgress function on the GET method is only triggered one time, and the setTimeout within the callback is never executed

I'm currently working on displaying a progress bar while fetching data from the backend API. However, I've encountered a couple of issues that I'm struggling to resolve. Firstly, the progress bar jumps from 0 to 100 without showing any actua ...

ASP.NET MVC controller encountering empty values through Ajax

I have attempted the suggested methods but still seem to be unable to resolve the issue. I am passing a list of objects through Jquery Ajax, however, it appears that the controller is receiving null values (even though it's acknowledging the list coun ...

Customizing AngularJS Scripts to Include Target Blank

I'm feeling a bit lost. I need to include a target="_blank" on my anchor link. The issue is that the anchor tag is linked to a script in angular. I am not familiar with this JavaScript framework. I have tried searching through the documentation for po ...

Comparing "if" and "else" within the XMLHttpRequest() function will not

function banUser() { var userToBan = document.getElementById('userToBan').value; var cid = document.getElementById('chatId').value; if (userToBan.length <= 0) { var x = document.getElementById("banerror"); x.innerHTML ...

A guide on effectively mocking functions in Jest tests with Rollup.js

I am currently in the process of developing a React library called MyLibrary, using Rollup.js version 2.58.3 for bundling and jest for unit testing. Synopsis of the Issue The main challenge I am facing is with mocking a module from my library when using j ...

Explore the functions of jQuery's .css() method and the implementation of

Could use some assistance with the .css() method in jQuery. Currently working on a mouseover css menu, and encountering an issue when trying to include this code: $(this).siblings().css({backgroundColor:"#eee"}); at the end of my script. It seems to int ...

Looking for assistance with PHP if statement and troubleshooting iFrame issues

Using the PHP if statement below on my website: <?php if(empty($_GET['tid'])) echo '<iframe src="http://tracking.mydomain.com/aff_goal?a=33&goal_id=47" scrolling="no" frameborder="0" width="1" height="1"></iframe>'; ...

Is the maxlength attribute malfunctioning in Chrome and Safari for HTML forms?

<input type="number" maxlength="5" class="search-form-input" name="techforge_apartmentbundle_searchformtype[radius]" id="techforge_apartmentbundle_searchformtype_radius"> I found this HTML snippet using the Firebug tool in Chrome. In Chrome and Saf ...

Error occurred due to 'NoneType' object lacking the 'split' attribute while attempting to send a post request through Ajax to Django

I recently created a method in my views.py file to serve as an API for user login using Django 2.1. The method works perfectly fine when tested with POSTMAN, but I encountered an issue when trying to use AJAX to send requests to the API. Instead of receivi ...

Looking to trigger a PHP page by clicking on a div?

Is there a way to trigger a PHP page call when a user clicks on a <DIV> with AJAX? Additionally, can the text of the DIV be changed to display "LOADING....." simultaneously? I lack knowledge about AJAX. Could you please provide me with more details ...

Concealing a hyperlink depending on the value chosen in a dropdown menu

Looking for guidance on how to use jQuery to read the current value of a drop-down list and hide a specific link based on that value. The drop-down list is for selecting the language/locale. For example, when "English" is selected, I want the link to be h ...

PHP code cannot be executed due to a problem with Angular routing

I stumbled upon this previous discussion during my search for assistance with a particular problem, but unfortunately there were no responses that could provide a solution. The issue I am facing involves submitting a form and expecting to receive a php va ...

JavaScript - AJAX Call Terminated after a Period on Secure Socket Layer (SSL)

Currently, my AJAX calls over an SSL connection using the Prototype JS framework run smoothly initially. However, after 10 seconds of being live on the page, they start failing with a status of 0 or 'canceled' in the Network Inspector... This is ...

What is the best way to transform parameters in axios requests into objects?

Within my ReactJs app, I have implemented the following code: axios .get(`/shipping/get-shipping-values`, { params: { products: [ { ...product, quantity, }, ], ...

Tips on successfully passing multiple keys and their associated HTML tag attributes in a React application

One of my links, specified with an a-tag, appears in this manner: <a href={ item.htmlReportUrl } target="_blank" rel="noopener noreferrer"> {item.htmlReportText}</a> The values for the href and the linktext are sourced from the following: ro ...

ng-if not functioning properly in Internet Explorer 8

Currently, I am developing a substantial Angular application that needs to be compatible with IE8. However, we are encountering performance problems as we implement ng-show extensively on the homepage. I am considering using ng-if to completely remove pa ...

What happens when browsers encounter unfamiliar at-rules?

CSS at-rules have been part of CSS since the days of CSS2. As CSS evolves with new specifications like @supports, it's interesting to see how different browsers handle unsupported rules. Do major browsers simply ignore unrecognized rules, or do they f ...