Choose all from the list of categories

  function CheckItems(chk)  
    {  
       if(document.myform.brandid.value!="Check all"){  
        for (i = 0; i < chk.length; i++)  
        chk[i].checked = true ;  
        document.myform.brandid.value="UnCheck all";  
       }else{  
        for (i = 0; i < chk.length; i++)  
            chk[i].checked = false ;  
            document.myform.brandid.value="Check all";  
       }  
    }  

I am trying to create a form with checkboxes organized by categories:

--category FRUITS--  
 checkbox for Select All   
 checkbox for Apple  
 checkbox for Mango  

--category VEGETABLES--  
 checkbox for Select All   
 checkbox for Carrots  
 checkbox for Cabbage  

How can I implement a select all functionality where checking the "Select All" option under a specific category will only select all items belonging to that category, such as selecting all fruits will check Apple and Mango checkboxes?

Answer №1

To begin, start by creating your form and assigning a class to group elements

<form name="my_form" id="my_form">
<h1>Types of Animals</h1> 
    <input type="checkbox" value="" id="all_animals" /> Select All <br />
    <input type="checkbox" value="Dog" class="animals" /> Dog <br />
    <input type="checkbox" value="Cat" class="animals" /> Cat

<h1>Colors</h1> 
    <input type="checkbox" value="" id="all_colors" /> Select All <br />
    <input type="checkbox" value="Red" class="colors" /> Red <br />
    <input type="checkbox" value="Blue" class="colors" /> Blue
</form>

Next, implement an unobtrusive function to handle the specified actions

function ToggleCheck() {  
  var allAnimals = document.getElementById('all_animals'), 
  allColors = document.getElementById('all_colors'), 
  formElements = document.forms.my_form.elements;

  allAnimals.onclick = function() {   // add a click event for the first group (animals)
  if (allAnimals.checked) {        // if SELECT ALL is clicked
     for (var i = 0; i < formElements.length; i++) {  // iterate over all form elements
        if ( formElements[i].type === 'checkbox' && formElements[i].className === 'animals' ){ // check if checkbox belongs to animals group
           formElements[i].checked = true;  // mark it as checked
        }
     }
   }
  else {  // if SELECT ALL is unchecked 
     for (var i = 0; i < formElements.length; i++) {  // loop over all form elements 
        if ( formElements[i].type === 'checkbox' && formElements[i].className === 'animals' ) { // check if checkbox belongs to animals group
           formElements[i].checked = false;  // unmark it
        }
      }
    }
   };

  // handle the same logic for colors 
  allColors.onclick = function() {
  if(allColors.checked){
     for (var i = 0; i < formElements.length; i++) {
        if ( formElements[i].type === 'checkbox' && formElements[i].className === 'colors' ){
           formElements[i].checked = true;
        }
     }
   }
  else {
     for (var i = 0; i < formElements.length; i++) {
        if ( formElements[i].type === 'checkbox' && formElements[i].className === 'colors' ){
           formElements[i].checked = false;
        }
      }
    }
   };
}

window.onload = ToggleCheck;  // execute the function upon page load

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

What is the best way to avoid the pipe symbol in jade formatting?

When working with jade, the pipe symbol (|) is utilized for displaying plain text. But what if you need to actually write it on the page? Is there a way to escape it in Jade? ...

Using jQuery to dynamically add or remove table rows based on user inputs

Apologies if this is too elementary. I am attempting to insert rows into a table if the current number of rows is less than what the user requires. Simultaneously, I need to remove any excess rows if the current number exceeds the user's specificati ...

What is the process for loading Syntax Highlighter on pages with pre tags?

As a Blogger, I often find myself in need of demonstrating codes on my blog. To achieve this, I have been using a Syntax Highlighter developed by Alex Gorbatchev. However, a recurring issue I face is that the files load on every single page of my blog, cau ...

What steps are involved in incorporating watchify into my gulp file?

I am looking to streamline the process of packing React using gulp in my nodeJS application. Below is the gulpfile I have set up: let gulp = require('gulp'); let uglify = require('gulp-uglify'); let browserify = require('browseri ...

Trail of crumbs leading to pages displayed in a div container

My website is designed with only one page where all other pages are loaded within a div. I am looking to implement breadcrumbs to keep track of the pages loaded inside the div. However, the solutions I have found online only work for pages loaded in the en ...

`How can I integrate jQuery UI using Webpack in my project?`

I recently initiated a fresh project utilizing React Slingshot and am experimenting with integrating jQuery UI accordions. I've included the jQuery UI plugin using NPM with the command npm install --save jquery-ui. From what I comprehend, Webpack auto ...

Blending Multi-Dimensional Arrays

I am looking to merge two arrays based on matching values of group_id, user_id, and unit_id. If these values exist in one array but not the other, I want to include a placeholder string to show that there was no corresponding value. Array 1: Array ( ...

What is a more efficient method for incorporating optional values into an object?

Currently, I am utilizing the optional addition feature in this way: ...(!!providerId && { providerId }), ...(!!practiceId && { practiceId }), Is there a more elegant shorthand method to replace this logic, such as: yield createRemark ...

What is the best way to clear radio button selections in a form using reactjs?

I designed a survey form with 4 radio buttons for a single question. I also included buttons to submit the form and clear input fields. However, when I click on "Clear Input," the checked radio buttons do not get cleared. How can I achieve this using the r ...

Column alignment issue detected

Can you help me with aligning the data in my column status properly? Whenever I update the data, it doesn't align correctly as shown in the first image. https://i.stack.imgur.com/300Qt.png https://i.stack.imgur.com/4Dcyw.png $('#btn_edit' ...

utilizing services across multiple controller files

Service - optionService.js controllers - app.js & welcomeCtrl.js & otherCtrl.js app.js var app = angular.module('mainapp', ['mainapp.welcome','optionServiceModule']); app.controller('mainappCtrl', functio ...

Creating layers of object declarations

Looking for assistance on the code snippet below. type Item = { id: number; size: number; } type Example = { name: string; items: [ Item ]; } var obj: Example = { name: "test", items: [ { i ...

Having trouble generating a readable output bundle due to the following error message: "The entry module cannot be found: Error: Unable to resolve './src/index.js'"

I'm currently working with Webpack version 6.14.8 within an Asp.net Core Razor Pages project in Visual Studio 2019. My objective is to generate a readable output file, and here's the directory structure I've set up: |-->wwwroot -----> ...

I'm seeking an easy method to adjust the x and y coordinates of a popup rectangle with a fixed size. Can anyone provide

Is there a way to create a simple pop-up rectangle, possibly using jQuery or a similar tool, that presents a scaled-down canvas view of a larger browser window (1000px x 1600px), allowing users to click and determine the x/y position within the full window ...

Adding elements from one array to another array of a different type while also including an additional element (JavaScript/TypeScript)

I'm having trouble manipulating arrays of different types, specifically when working with interfaces. It's a simple issue, but I could use some help. Here are the two interfaces I'm using: export interface Group { gId: number; gName: st ...

Locating a specific element in an array with varying values in a string array using Java

Here is a string array I'm working with: String[] s={"0010", "0110", "1010", "1110", "0001", "0011"} I am looking to identify pairs of elements that have changed within the array. In this case, only one element changes for every string. For example ...

Issue encountered: Failure to locate module 'socket.io' while attempting to execute a basic server JavaScript file

Below is my server.js file that I am attempting to run using node server.js: var app = require('express')(); var http = require('http').createServer(app); var io = require('socket-io')(http); //also tried socket.io instead of ...

Confirm the email address using the autocomplete feature in the field

I'm currently utilizing Material UI to design an autocomplete field with multiple inputs that gives users the option to either choose from existing email addresses or input their own. An example of what I'm trying to achieve can be seen here: ht ...

Learn how to continuously update the current timestamp in PHP using jQuery or JavaScript every second

I am currently developing a PHP cart timer script that utilizes PHP along with jQuery and JavaScript. By using the set-interval function, I am able to continuously retrieve the current time-stamp in PHP. Once the first product is added to the cart, the t ...

Unique syntax using markdown-react

I want to customize the syntax highlighting in react-markdown. Specifically, I would like to change the color of text inside {{ }} to blue while still maintaining the correct formatting for other elements, such as ## Header {{ }} import React from " ...