Displaying all divs when the checkboxes are unchecked

My code displays a product list with various details stored in different divs based on data attributes like brand, store, and more. A friend helped me develop a filter using checkboxes for record selection. However, I need to make a small modification to it. Take a look at the code below:

<html>
      <head>
        <meta charset="utf-8">
        <title>Product List</title>
      </head>
      <body>
        <div>
     </form>
      </body>
    </html>
    

CSS:

.hidden {display: none;}

    .content {border-radius: 5px; border: 1px solid #bbb;padding: 5px; margin: 5px; float: left;}
    #filter {clear: left;}
    

JavaScript:

var filterContentForm = function(content, form){  
      // JavaScript Code Goes Here
    };

    filterContentForm('.content', '#filter'); 
    #filter {clear: left;}
    

The code above works well, but I just need one small adjustment. At the start, I want both "Nike" and "Shoes" checkboxes to be unchecked and all records visible by default. However, when I remove the 'checked' attribute from them, the filtering does not work as expected.

I'm seeking guidance on how to uncheck all checkboxes initially and have the filtering work properly after selecting the desired options. Thank you for your assistance.

Answer №1

It appears that there may be a glitch in your filter code. Be sure to include the jquery js file in the header section of your HTML!

To switch between checked and unchecked states for checkboxes and/or radio buttons, simply add or remove the checked attribute from the tag

<input type="checkbox" 
           name="category" 
           value="shoes" **checked**> 

Answer №2

Alright, here's the issue at hand:

You're evaluating the condition below

if(show < l)

where show represents the count of checked filterCategories [in this scenario: brand and category], compared to l, which indicates the total number of filterCategories available.

When only one of the categories is checked, this condition becomes true, triggering the following code:

   `$this.addClass('hidden');
    all++;`

This causes your all++ to reach the value of contents.length, leading to the execution of the subsequent code block:

  if(all > contents.length - 1) 
  contents.removeClass('hidden');

resulting in overriding filters and displaying all items [the divs in this case]

To resolve this issue, consider the following code snippet. The addition of the activeFilterCount variable is key. Replace your code starting from var show=0,i; up to all++;} with the following:

var show = 0, i, activeFilterCount=0;
                for(var c in checkBoxGroups){
                  var n = checkBoxGroups[c], 
                      d = $this.data(c);
                  if(n.ch.length > 0){
                      activeFilterCount++;
                  }
                  for(i = 0; i < n.ch.length; i++){<br>
                    if(d === n.ch[i]) {
                      show++; break;
                    }
                  } 
                }
                if(show < activeFilterCount) {
                  $this.addClass('hidden');
                  all++;
                }

I know it's a bit lengthy, but I hope it provides clarity! Feel free to reach out if you need further explanation.

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

The layout of the keyboard in Cordova has been altered

Just starting out with my first Cordova app and I'm working on a simple login form. The issue I'm facing is that whenever I click on an input element, the keyboard pops up and completely messes up my layout, which should be straightforward. Has ...

A method for accessing a text file from a pastebin using CORS

My goal is to utilize CORS for fetching code snippets from a pastebin and then executing them in a web browser. Here is some work-in-progress code: http://www.example.com/code-snippets.html The code is syntax highlighted with options to run it, etc. I ...

Routing WebSocket connections with Node.js

Currently, I am in the process of developing a chat application for my company which will run on node js with websocket (ws). The app is designed to cater to various departments within the organization, each with its own set of users. My goal is to ensure ...

Tips for stopping automatic scrolling (universal solution)

Issue or Inquiry I am seeking a way to disable actual scrolling on an element while still utilizing a scrollbar for convenience (avoiding the need for manual JavaScript implementations instead of relying on browser functions). If anyone has an improved s ...

Integrate a feature in your form that allows users to preview and edit their submission before finalizing

I've set up my HTML form with the following structure: <div class="container"> <div class="form-group" ng-controller="studentController"> <form role="form" class="well form-horizontal" id="registerForm" name="forms.register ...

What is the process for converting a JSON File into an array using javascript?

Hey there, I'm new to programming so please bear with me XD. I've been struggling for 2 days trying to figure this out with no luck. So here's the deal - I have a chart in JavaScript that is pulling data from a file called test.json, which ...

Using a combination of stringify, regular expressions, and parsing to manipulate objects

As I review code for a significant pull request from a new developer, I notice their unconventional approach to editing javascript objects. They utilize JSON.stringify(), followed by string.replace() on the resulting string to make updates to both keys a ...

Sending data between controllers in AngularJS

As a newcomer to Angular, I am facing challenges in understanding how to utilize a Service to transfer data from one controller to another. My experience with Angular so far has involved successfully calling controllers and passing data to them from withi ...

Unable to render Javascript model in THREE JS

I am facing an issue with this code below as I can't seem to load the model. loader = new THREE.JSONLoader(true); loader.load("modelo.js" , function ( geometry, materials) { mesh = new THREE.Mesh( geometry, ...

What steps should be taken to incorporate a user input space similar to the one found in the Wordpress new post section

I am looking to incorporate a user input section on my website similar to the one found in WordPress for creating new posts. I would like this area to have all of the same tools available, such as adding hyperlinks, bolding text, and uploading images. Ca ...

The Stylish Choice: Materialize CSS Dropdown Selector

I am currently integrating Materialize CSS into my application and have used media queries to ensure that the layout is responsive. However, I am facing an issue with a select dropdown element. It works fine on laptops but does not allow for selecting any ...

Reading through various files simultaneously using JavaScript: iterating over the same file in a for loop

I'm currently working with the following code: function handleFiles(e) { var filesInput = $('#files').prop('files'); var i, f; for (i = 0, f = filesInput[i]; i != filesInput.length; ++i) { var name ...

After implementing two hooks with null properties, the code fails to execute

Recently, I encountered an issue with this section of the code after upgrading react scripts from version 2.0 to 5.0. const { user, dispatch } = useContext(AuthContext); const { data } = useFetch(`/contracts/${user.contractType}`); if (!user) { ...

The autocomplete feature triggers the closure of the bootstrap dropdown when selecting

I have developed a basic material auto complete feature. Using Angular 5 and a bootstrap 4 dropdown to showcase a form. The issue I am facing is that when I place the autocomplete inside the dropdown and choose an item from it, the entire dropdown closes ...

What steps can be taken to ensure that the getData() function is executed prior to the MovieCard

Struggling to work with async functions while creating a random movie generator app using react js and material ui. It seems like the data retrieval from the API is not quick enough for my component. How can I fix this issue? Is there a way to ensure tha ...

z-index in CSS causes links to conflict

I am currently working on a project that requires an image to be displayed prominently on the website along with some links positioned behind it. However, I'm facing an issue where I can't click on the links after implementing z-indexes to layer ...

The functionality of my contact form is non-operational

I have been struggling with my contact form for months, trying various tutorials but still no luck. Please take a look at it here. This time, I followed this tutorial. Here's the code I have on my form from the first link: Contact Form ...

Unlocking Google contact pictures using Google contacts API - A step-by-step guide

Exploring the Google contacts API with Node.js I've successfully retrieved all the contacts via the Google feed API, but without images https://www.google.com/m8/feeds/photos/media/faizy04%40gmail.com/ya29.ZAFTNcQ6sEue40gFqH5h8h91k8LO8Bwvf50NUgQKKms ...

Discovering an item within an array of objects using the find method in Ajax

Within my backend PHP code, I iteratively define the following: foreach ( $data as $res ){ $approved[ ] = [ 'id' => $count, 'title' => "some title" ]; $count++;$title=... ) This eventually leads to the creation ...

Node-static is reporting that the localhost page cannot be located

I am currently attempting to serve static files using node-static. My plan is to eventually run this as a Windows service using nssm. I have successfully executed this process in the past, however for some reason it is not working now. Here is the code sn ...