Toggle the visibility of divs using jQuery for easy filtering

I am looking to enhance my filtering system by allowing users to apply and view multiple filters simultaneously. For example, I want to be able to select 'High' and 'pizza' filters and see the results that match both criteria. Currently, the system only allows for switching between filters and displaying results based on the single filter selected.

https://jsfiddle.net/f7srx0dd/

<div class="nav">
<a href="#" data-category-type="high">high</a>

<a href="#" data-category-type="low" data-category-name="air">low</a>

<a href="#" data-category-name="pizza">pizza</a>

</div>
<div id="Categories">
    <div class="hide" data-category-type="high" data-category-  name="pizza">high</div>
    <div class="hide" data-category-type="low" data-category-name="pasta">low</div>
    <div class="hide" data-category-type="low" data-category-name="pizza">low</div>
    <div class="hide" data-category-type="high" data-category-name="pasta">high</div>
</div>

$('.nav a').on('click', function (e) {
e.preventDefault();
var cat = $(this).data('categoryType');
var nam = $(this).data('categoryName');
$('#Categories > div').hide();
$('#Categories > div[data-category-type="'+cat+'"]').show();
$('#Categories > div[data-category-name="'+nam+'"]').show();

});

Answer №1

Your approach needs tweaking. Using $(this) won't fetch both the category and name at once.

When using the click function, $(this) only refers to the clicked element. In your scenario, the same element may not contain information for both the category and name.

Therefore, you should either update your HTML to include both data attributes in all anchor tags or adjust your function to fetch the category and name from a reliable source.

I'll provide a sample to clarify further.

This is an example with updated HTML where anchors have both data attributes:

<a href="#" data-category-type="high"  data-category-name="pizza">High and pizza</a>

https://jsfiddle.net/f7srx0dd/4/

Here's another example with updated javascript:

https://jsfiddle.net/f7srx0dd/5/

I hope you find these solutions helpful!

Answer №2

To keep track of which buttons you have selected, it is important to set up an on and off state for them. You can achieve this by adding a click event that toggles the 'selected' class on and off like so:

if ($this.hasClass('selected')) {
    $this.removeClass('selected');
} else {
    $this.addClass('selected');
}

After implementing this logic, you can loop through the links to display the selected ones.

I have made the necessary adjustments in your fiddle: https://jsfiddle.net/f7srx0dd/2/

Answer №3

When dealing with multiple filters, you can switch a class every time you click on a link. Keep in mind that this method works best with buttons rather than links, but for the sake of matching your HTML, we will use links.

$('.nav a').on('click', function (e) {
  $(this).toggleClass('active');
  $('#Categories > div').hide();

  $('.active').each(function() {
    var cat= $(this).data('categoryType');
    var nam= $(this).data('categoryName');
    $('#Categories > div[data-category-type="'+cat+'"]').show();
    $('#Categories > div[data-category-name="'+nam+'"]').show();
  });
});

This snippet of code toggles the class named active and goes through each selected item's categoryType and categoryName to decide what should be included in the filter.

Fiddle

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

An issue is encountered with the JavascriptExecutor while attempting to navigate to a different page using Selenium Webdriver

My goal is to capture user actions such as clicks, keypress, and other DOM events by adding JavaScript event listeners to the WebDriver instance. Everything works fine until I navigate to the next page, where I encounter an exception due to an undefined fu ...

Sending an Ajax request to the MVC Controller results in a response of "NOT FOUND"

Trying to use AJAX to call a MVC Controller action with certain parameters has been successful in the past within this application. However, for some reason, THIS SPECIFIC ONE is not functioning properly. function deleteDetail(button, tab) { var i ...

Storing a JavaScript variable into a JSON file to preserve data

Is it possible to save data from variables to a JSON file? var json_object = {"test":"Hello"} $.ajax({ url: "save.php", data: json_object, dataType: 'json', type: 'POST', success: ...

Retrieving the text from the img tag of a bs4.element.Tag

I have a question that needs to be addressed. My concern involves a list of bs4.element.Tags, similar to the one illustrated in the image below. The issue at hand is filtering out only the href tags that are preceded by an <img> tag. How can this s ...

Utilizing AngularJS routes to load a specific URL when accessing a page for the first time

Working on developing a Single Page Application using AngularJS, my configuration settings appear as follows: app.config(["$routeProvider", function($routeProvider) { return $routeProvider .when("/", { redirectTo: " ...

Unable to dynamically load a script located in the node_modules directory

This particular approach is my go-to method for loading scripts dynamically. import {Injectable} from "@angular/core"; import {ScriptStore} from "./script.store"; declare var document: any; @Injectable() export class ScriptService { private scripts: an ...

What is the reason for the malfunction of native one-time binding when using the `::` expression in Angular version 1.3.5?

I am having an issue with AngularJS's one-time binding feature using the :: expression. Despite my code setup, the values are still changing. I must be missing something crucial here. Consider this controller: $scope.name = "Some Name"; $scope.chang ...

The optimization of paths in Gulp with Browsersync

I am facing an issue with making a file request via ajax post request. I'm trying to figure out how to properly map the file path in my ajax call to match the server's path. I can't seem to understand why it's not working (previously u ...

Exploring the mern.io scaffolder tool - Unraveling the essence of the .need method

While exploring the code of the scaffolder mern.io, I came across an intriguing method called ".need". It appeared to be related to es6 classes, but unfortunately, I couldn't find any valuable information about it. Thus, I'm curious to know: what ...

Add a personalized class to a mat-tab within a mat-tab-group

I am looking to add unique styles to specific mat-tabs within a mat-tab-group based on a condition. The main mat-tab-group already has a default custom style that is functioning correctly. The styling is applied as follows: .mat-mdc-tab-group.round-tabs, ...

Code not displaying message in Console using jQuery each() function

I am currently stuck on a seemingly simple implementation of jQuery's each method. The code snippet I have below was taken from https://api.jquery.com/each/ as a reference to understand how the each method functions. Despite my attempts to test the co ...

The columns in the row are not fully filling up the container

I have a container with two rows inside. One of those rows contains several columns. My goal is to have four columns per line on mobile devices, which I achieved using "row-cols-4". However, on larger screens, I want all the columns to be on the same line, ...

Unusual images emerge following certain elements in this unique gallery

Looking for some advice on my image gallery created using an ordered list. The issue I'm facing is that the images are not all the same size, causing the 4th and 7th images to disrupt the layout. I have come up with a solution by using: ...

Using jQuery to remove the functionality of a file input button is ineffective

I am having trouble with an input type file element: <input type="file" name="val1" /> And I'm using this jQuery code: $("input[name='val1']").off("click"); However, the above script, which is already included in a $(function() { } ...

Tips for adding an array to a formData: incorporating an array with two values along with their corresponding keys

Snippet : const options = new RequestOptions({ headers: headers }); let myArray; myArray = [{ "subfolder_name": subfolder, "file_upload": file }]; let formData: FormData = new FormData(); formData.append("folder_name",folder ); formData.append("counse ...

Utilizing JQuery to send both files and text data via ajax请求

I am currently working on a Django web application that features a newsfeed functionality. Each newsfeed item includes a title, body, and image. Users can edit and update their newsfeeds, including adding new images. My current approach involves retrievin ...

Pagination with Ajax functionality integrated within jQuery tabs

I'm experiencing an issue with pagination within jQuery tabs. I've implemented Ajax pagination, which is working fine initially. However, when I click on a page number in the pagination for the second time, it breaks the link. To see how it' ...

Conceal the block quotes while substituting with a newline

My HTML page contains numerous comments enclosed in blockquotes. I attempted to implement a feature that allows users to hide all the comments with just one click by using the following JavaScript code: const blockQuotes = document.getElementsByTagName(& ...

Utilizing Boolean Operators in JavaScript with Thymeleaf: A Guide

When incorporating Boolean conditions in JavaScript with Thymeleaf using th:inline="javascript", an exception is thrown which appears as follows: org.xml.sax.SAXParseException; lineNumber: 14; columnNumber: 22; The entity name must immediately follow the ...

Where should uploaded files be stored using ng-flow?

Initially, I am utilizing the ng-flow, which is an html5 file upload extension built on the angular.js framework. After uploading my files and logging the event in the console, I'm uncertain about where and how to store them. Below is my HTML code w ...