What is the best way to incorporate functionalities for selecting all, deselecting all, and resetting all options within a checkbox list?

I recently undertook a tutorial challenge to create:

  1. Tick ALL boxes - Taco Everything
  2. Untick ALL boxes - Untaco Everything
  3. Delete ALL boxes - Eliminate all the 'dishes' in the menu added

I am grappling with this. While my code successfully adds items to the list when entered, the functionality for any of the above commands is not working. How can I achieve this using JavaScript?

const addItems = document.querySelector('.add-items'); //selects all form items
const itemsList = document.querySelector('.plates'); // selects plates area
const checkboxes = document.querySelector('.check__all'); // selects check all button
const uncheckboxes = document.querySelector('.uncheck__all'); // selects uncheck all button
const clearBoxes = document.querySelector('.clear__all'); // selects remove/clear all button
const items =  []; // empty array to store passed data

function addItem(e){
e.preventDefault(); 
const text = (this.querySelector('[name=item]')).value; 
const item = { 
  text,
  done: false
};

items.push(item); 
populateList(items, itemsList); 
localStorage.setItem('items',JSON.stringify(items)); 
this.reset();
}

function populateList(plates = [], platesList){
platesList.innerHTML = plates.map((plate,i)=>{ 
  return `
    <li>
    <input type = "checkbox" data-index = ${i} id = "item${i}" ${plate.done ? 'checked' : ''} />
    <label for="item${i}">${plate.text}</label>
    </li>
  `;
}).join(''); 
}

function toggleDone(e){
if(!e.target.matches('input')) return; 
const el = e.target;
const index = el.dataset.index;
items[index].done = !items[index].done;
localStorage.setItem('items',JSON.stringify(items));
populateList(items, itemsList);
}


addItems.addEventListener('submit', addItem);
itemsList.addEventListener('click', toggleDone);
populateList(items, itemsList);
(CSS CODE SNIPPET)
(SVG IMAGE CODE)

I have attempted different approaches but none seem to be effective.

Answer №1

If the inputs provided are checkboxes, this code should function properly. In case they are not checkboxes, please specify the type of inputs and I will make necessary adjustments.

function checkAll () {
  let inputs = document.querySelectorAll("input[type=checkbox]")
  inputs.forEach(item => {
    item.checked = true
  })
}

function uncheckAll () {
  let inputs = document. querySelectorAll("input[type=checkbox]")
  inputs.forEach(item => {
    item.checked = false
  })
}

Answer №2

Here is a suggested solution:

checkboxes.addEventListener('click', checkAll);
uncheckboxes.addEventListener('click', unCheckAll);


function checkAll(e) {
  var listItemChk = document.querySelectorAll('.plates li input');

  if (listItemChk && listItemChk.length > 0) {
    Array.from(listItemChk).forEach(function(inputChk){
      inputChk.checked = true;
    });
  }

}

function unCheckAll(e) {
  var listItemChk = document.querySelectorAll('.plates li input');

  if (listItemChk && listItemChk.length > 0) {
    Array.from(listItemChk).forEach(function(inputChk){
      inputChk.checked = false;
    });
  }

}

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

Issues with Bootstrap Container on Smartphones

Currently tackling the responsive design aspect of my website, however, I've encountered a bug specifically with mobile devices. Interestingly, testing it on my desktop browser proves smooth sailing, but when attempting on my iPhone, I faced some chal ...

Implementing a 3D cylinder chart with ReactJS using Highcharts

I've been attempting to incorporate a cylinder 3D chart into my react component, but I keep encountering this error message. Error: Highcharts error #17: www.highcharts.com/errors/17/?missingModuleFor=cylinder missingModuleFor: cylinder The code in ...

The PrimeNG Tree component offers a range of unique features

Encountering an issue with the PrimeNG tree in angular2 Let's take a look at the code snippet from product_tree.component.ts : constructor(private http: HttpClient, private productsService: ProductsService) { this.productsService.getProductsClasse ...

Leveraging the power of Nuxt.JS (Vue.JS) and VueX to connect a form to an array of objects within a VueX store

Seeking assistance with binding a form to a list of Defaultsettings obtained from an array of objects in NuxtJs and VueX. The list of Defaultsettings includes: Name defaultsetting (text) Active (a switch button that determines if the defaultsetting will ...

Tips for incorporating an additional dataset bar using chart.js

I'm having a bit of trouble trying to modify the following script. Currently, it only displays one bar per label, but I need it to show 2 bars per label. Despite my numerous attempts using different variations with and without commas and "{}", I can&a ...

PHP code for uploading multiple images at once

I am currently facing an issue with uploading multiple files at once and not getting the desired result. Below is my code snippet: <?php if (isset($_FILES['uploadfiles'])) { print_r($_FILES); } ?> <form action="index.php" method="po ...

The Express.io platform is having trouble loading the JavaScript file

Currently, I have an operational Express.io server up and running. However, I am encountering issues with the proper loading of my Javascript files. Here is a snippet from my Jade file: html head h1 Test index body script(src="/so ...

managing the HTML class names and IDs for various functions such as styling, jQuery interactions, and Selenium automation

While there is an abundance of articles on writing clean HTML/CSS, one aspect that seems to be lacking advice is how to organize class names and IDs for different purposes such as design, jQuery, and Selenium testing. The challenge lies in deciphering the ...

Utilizing App Script for Filtering Data with Multiple Criteria

Having trouble transferring data from a data sheet to my report sheet using multiple criteria for matching. I wrote some code that worked, but it's returning all data instead of filtering by criteria. I want the function to search for column criteria ...

Looking to implement an automatic refresh for the seconds in my Node.js application

Currently in the process of developing a web application that displays the local time of a specified timezone. I am utilizing a timezone API and seeking a method to automatically refresh the page or call the API every second in order to update the seconds ...

Determine the sphere's color using the coordinate system in three.js

Is there a way to customize the color of this sphere rendered in three.js based on its coordinates? For instance, can I make the top half of the sphere red and the bottom half black? var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamer ...

How can you retrieve the value of a CSS file in Javascript and CSS?

Imagine there is an element with the class .selector. This class defines its style. Once the page has finished loading, some JavaScript code is executed - the specifics are not important. What matters is that the CSS properties have set the object's ...

How to fix the jquery error "Uncaught TypeError: Cannot read property 'style' of null" in an elegant way?

In my HTML code, I created a div element. When a user clicks a button, I run a simple JavaScript script to try to hide it: document.getElementById("samplques").style.display = "none"; However, I encounter an error when I execute the script: cannot rea ...

Is there a way to make Outlook show only the caption of a link instead of the entire URL?

In my PDF file, I have set up a button for sending an email. The email is a request that needs approval or denial. I want the recipient to respond with just 2 clicks: Click on either "Approve" or "Deny" (a new email will pop up) Click on "send" - and it& ...

Create a div element that expands to occupy the remaining space of the screen's height

I am trying to adjust the min-height of content2 to be equal to the screen height minus the height of other divs. In the current HTML/CSS setup provided below, the resulting outcome exceeds the screen height. How can I achieve my desired effect? The foote ...

The MUI Select event is coming back as undefined

I am facing an issue with a Select component in my MUI form. Here is my current state: const [formdata, setformdata] = useState({}); This is my event handler: const onchangehandle = (e) => { setformdata((prevState) => ({ ...prevState, [e.target. ...

Ensure that each function is completed before proceeding to the next one

I've encountered an issue with my react app. After a user submits a form, I need a modal to open and the user's response to be stored in state. Then, based on this response, I have to execute some business logic before finally submitting the form ...

How can I alter the position of the scrollbar in a nested div structure in CSS?

Within my nested div structure, I have an inner div that functions as an auto scroller. However, this inner div is contained within another outer div, which itself is positioned inside yet another outer div. The scroller is only visible within the first ...

Point the direction to nextjs and react native expo web

I am currently working on redirecting a URL to another within my website, specifically in Next.js and Expo React Native Web. While I don't have an actual "About" page, I do have other pages nested under the "about" folder and am aiming to direct any ...

Gather information from "div" tag with the class attribute using Python

I am looking to extract specific financial data (referred to as the Key data) that is housed within <div> </div> tags. I then aim to consolidate this extracted information into an excel sheet which already contains additional harvested data. Th ...