Trapped in the JavaScript Checkbox Filter Maze

After successfully creating a javascript-only filter, I have hit a roadblock and could really use some assistance.

The filter is divided into "days" and "events".

When a user clicks on a day or multiple days, the events for those selected days are displayed.

Moreover, users can further narrow down their selection by clicking on specific events to only display those particular events for the selected days.

I have managed to get this functionality working, but I am struggling with making it work the other way around. If they have only selected the event(s) without choosing a day, nothing is shown.

Additionally, I am exploring how to incorporate a "show all" checkbox that would uncheck other boxes while displaying all dates/events.

function change() {
  let results = Array.from(document.querySelectorAll('.result > div')),
    dayChecked = document.querySelectorAll('.filter input.day:checked'),
    eventChecked = document.querySelectorAll('.filter input.event:checked');
  // Hide all results
  results.forEach(function(result) {
    result.style.display = 'none';
  });
  // Filter results to only those that meet ALL requirements:        

  filterdayOrevent(dayChecked);

  if (eventChecked.length != 0) {
    filterdayOrevent(eventChecked);
  }

  function filterdayOrevent(dayOreventChecked) {
    results = Array.from(dayOreventChecked).reduce(function(sum, input) {
      const attrib = input.getAttribute('rel');
      return sum.concat(results.filter(function(result) {
        return result.classList.contains(attrib);
      }));
    }, []);
  }
  // Show those filtered results:
  results.forEach(function(result) {
    result.style.display = 'block';
  });
}
change();
<div class="filter">
  <div class="checkbox">
    <label><input type="checkbox" rel="" class="" onchange="change()" />Show All</label>
  </div>
  <h1>Select day</h1>
  <div class="checkbox">
    <label><input type="checkbox" rel="friday" class="day" onchange="change()" />Friday</label>
  </div>
  <div class="checkbox">
    <label><input type="checkbox" rel="saturday" class="day" onchange="change()" />Saturday</label>
  </div>
  <div class="checkbox">
    <label><input type="checkbox" rel="sunday" class="day" onchange="change()" />Sunday</label>
  </div>
  <h1>Select event</h1>
  <div class="checkbox">
    <label><input type="checkbox" rel="screening" class="event" onchange="change()" />Screening</label>
  </div>
  <div class="checkbox">
    <label><input type="checkbox" rel="seminar" class="event" onchange="change()" />Seminar</label>
  </div>
  <div class="checkbox">
    <label><input type="checkbox" rel="social" class="event" onchange="change()" />Social</label>
  </div>
</div>
<P></P>
<div class="result">
  <div class="friday screening">Friday / Screening</div>
  <div class="friday seminar">Friday / Seminar</div>
  <div class="friday social">Friday / Social</div>
  <div class="saturday screening">Saturday / Screening</div>
  <div class="saturday seminar">Saturday / Seminar</div>
  <div class="saturday social">Saturday / Social</div>
  <div class="sunday screening">Sunday / Screening</div>
  <div class="sunday seminar">Sunday / Seminar</div>
  <div class="sunday social">Sunday / Social</div>
</div>

Answer №1

Make sure to only apply the day filter if there is at least one day checked, similar to how you handled the Events filter. Otherwise, without this logic, both the day and event filters will try to filter an empty array.

if(dayChecked.length != 0){
  filterdayOrevent(dayChecked);
}

To manage the "Show All" checkbox, create a separate function for it with its own set of actions. Once you have reset all other filters (unchecked them), simply trigger the change function.

function showAll() {
  let isChecked = document.getElementById('showAllCheck').checked;
  // If Show All is checked, uncheck all other checkboxes before calling change()
  if(isChecked){
    let filters = document.querySelectorAll('.filter input');
    Array.from(filters).forEach(function(filter) {
      filter.checked = false;
    });
  } 
  change();
}

// Rest of the JavaScript functions remain the same...

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

Guide to Implementing a Single Trigger Click with jQuery for Window Scrolling

I have implemented JavaScript code for a button that loads additional posts from the database. The button has the class of .getmore. My goal now is to enable infinite scroll so that users do not have to manually click the button. In order to achieve this ...

How can I automatically disable certain checkboxes when a specific radio button is selected?

Looking to disable certain checkboxes when a specific radio button is selected. For instance, selecting the first radio button with the id="pz1" should disable checkboxes with matching id values from the thisToppings array. Each radio button cor ...

Difficulty accessing context.params query in Next.js Dynamic Path

I've almost completed setting up a dynamic page in Next.js using getStaticPaths(), but I'm running into an issue with the getStaticProps() function not referencing the URL query correctly to load the relevant information. Here is my code: //Get ...

How do I connect to a different application's view?

When working with a view that has tiles, I am looking to click on one of them and be directed to a different application that I have created. In typical cases, I would specify the view folder for navigation. However, when attempting something similar for ...

Retrieve the outcome of a mongoose query within a designated function

Seeking help with returning a result from my mongoose find operation. While similar questions have been asked before, this one is unique. Here's an example of my user: let UserSchema = new mongoose.Schema({ variable: {type: mongoose.Schema.Object ...

Tips for organizing date columns in Bootstrap-Vue when utilizing a formatter for presentation purposes

I am working with a table containing date objects, and I have transformed them for display using the following code: { key: "date", formatter: (value, key, item) => { return moment(value).format("L"); }, sortable: true } However, this ...

A method for dividing a 1D numpy array into segments, where the length of each segment is determined by a specific condition

Recently I started learning Python and programming in general, and I would appreciate some guidance. I have two 1D arrays for data and time. Each time element corresponds to a data element, reflecting a full day of measurements. My objective is to divide ...

Combining two geometries with indexes into a BufferGeometry

Currently, I am utilizing a fixed set of data that contains indices, vertices, and colors, along with multiple instances of THREE.Geometry to populate a scene with objects. This process is quite slow, as it involves adding and removing numerous objects at ...

Ensuring the correctness of phone numbers by validating them with country codes through the use of

I'm currently working on validating phone numbers using intl-tel-input, following the example provided at Below is the code snippet I've been using: var telInput = $("#phone"), errorMsg = $("#error-msg"), validMsg = $("#valid-msg"); // initial ...

Is there a way to ensure the functionality of this code without exposing my API keys? I am currently developing an application using Node.js, Angular, and Express

I have come across an issue with my code where process.env is not working within a specific function. I need to find a way to call process.env without displaying my keys. If I don't add my keys, the API call won't function properly. What options ...

Adjust font size using jQuery to its maximum and minimum limits

My jQuery script enables me to adjust the font-size and line-height of my website's CSS. However, I want to restrict the increase size to three clicks and allow the decrease size only after the increase size link has been clicked - ensuring that the d ...

Display the precise outcome for each division following a successful AJAX callback

I’m facing a challenge in getting individual results for each item after a successful AJAX callback. Currently, I am able to retrieve results, but when there are multiple items, all displayed results are being added to each div instead of just the corres ...

Navigating C pointers with casting types

#include<stdio.h> int main() { int a; char *x; x = (char *) &a; a = 512; x[0] = 1; x[1] = 2; printf("%d\n",a); return 0; } I'm struggling to understand how the output ends up being 513 or if i ...

Creating a loop in a column-based carousel without using JavaScript

I'm currently working on developing a carousel using JavaScript or jQuery. I've attempted the code snippet below, but I'm having trouble getting it to display in 3 or 4 columns. While I understand that Bootstrap can handle this easily, I&apo ...

The issue of "undefined is not a function" is arising when trying to use the session in NHibernate with a mongo store

In my MongoDB database, I have a collection named 'Sessions' within the 'SessionStore' to store session state. To manage sessions, I am using express-session. Below is the code snippet used to set up sessions: var session = requi ...

Working with Angular: Accessing SCSS variables from style.scss using JavaScript inside a component

I am working on an Angular 9 application that utilizes Angular Material and has two themes, namely dark and light. These themes are defined in the style.scss file as follows: $rasd-dark-text-color: mat-palette($mat-grey, 300); $rasd-light-text-color: mat-p ...

Transform your CSS styles into Material-UI makestyles

I am looking to implement an IconButton with a website preview feature that appears when the user hovers over the help icon. I came across a similar solution using CSS, but I need to convert it to Material UI. Here is the CSS code that needs to be converte ...

Determine if the input text includes a URL when a key is pressed using jQuery

I am currently working on a feature to detect URLs when users input content manually, paste a link, or a combination of both. My goal is to retrieve the contents of the URL, similar to how Facebook handles it, when the first detection occurs. Here is the ...

Find the height of the viewport using jQuery, subtracting (n) pixels

Apologies if the topic seems puzzling, I couldn't find a better way to explain it. I utilized jQuery to adjust the height of a div to match the size of the viewport. var slidevh = function() { var bheight = $(window).height(); $(".container" ...

Incorporate relationships while inserting data using Sequelize

vegetable.js ... var Vegetable = sequelize.define('Vegetable', { recipeId: { allowNull: false, ... }, name: { ... }, }); Vegetable.association = models => { Vegetable.belongsTo(models.Recipe); }; ... recipe.js ... var Recipe = sequeliz ...