What is the process for choosing all items and then canceling the selection in a

I utilized the information on this webpage to generate the following code snippet: https://getbootstrap.com/docs/5.0/forms/checks-radios/#indeterminate

Upon clicking the checkbox with the ID of (flexCheckIndeterminate), all checkboxes located below it will be marked as selected, and clicking it again will deselect all the checkboxes below it.

Is there a way to achieve this functionality using JavaScript without relying on jQuery?

 <!doctype HTML>
 <html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="781a17170c0b0c0a1908384d5648564a">[email protected]</a>/dist/css/bootstrap.min.css" 
       rel="stylesheet" integrity="sha384- 
       EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

    <title>Hello, world!</title>
  </head>
  <body>
    <h2>Bootstrap Table Checkbox Select All and Cancel</h2>
    <div class="container">
      <table class="table table-bordered table-hover" id="dataTable" width="100%" cellspacing="0">
        <thead>
            <tr>
                <th>
                  <div class="form-check">
                    <input class="form-check-input" type="checkbox" value="" 
                      id="flexCheckIndeterminate">
                    <label class="form-check-label" for="flexCheckIndeterminate">                      
                    </label>
                  </div>
                </th>
                <th>#</th>
                <th >Name</th>
                <th > ID</th>
                <th >Date & Time</th>
                <th >Check-in</th>                
            </tr>
        </thead>
        <tbody>
            <tr>
                <td><div class="form-check">
                  <input class="form-check-input" type="checkbox" value="" id="defaultCheck1">
                  <label class="form-check-label" for="defaultCheck1">                                                    
                  </label>
                </div>
                </td>
                <td>1</td>
                <td>Safaa</td>
                <td>20421</td>
                <td>12/2/2021 16:40</td>
                <td>Yes</td>
              </tr>

            <tr>
                <td><div class="form-check">
                  <input class="form-check-input" type="checkbox" value="" id="defaultCheck2">
                  <label class="form-check-label" for="defaultCheck2">                                                    
                  </label>
                </div>
                </td>
                <td>2</td>
                <td>Noor</td>
                <td>19091</td>
                <td>15/2/2021 16:40</td>
                <td>No</td>
                 </td>

            </tr>
        </tbody>
     </table>
    </div>
  

    <!-- Optional JavaScript; choose one of the two! -->

    <!-- Option 1: Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="accec3c3d8dfd8decddcec99829c829e">[email protected]</a>/dist/js/bootstrap.bundle.min.js" 
     integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" 
      crossorigin="anonymous"></script>

    

   

  </body>
 </html>

Answer №1

It seems like you are encountering issues related to handling the indeterminate state in pure JavaScript. If you want all checkboxes to be either checked or unchecked when the indeterminate state is selected, you need to first set indeterminate = false, and then proceed to set the desired state as checked or unchecked.

Below is a snippet of code that may help you understand this concept better:

Source: https://css-tricks.com/indeterminate-checkboxes/

var parentCheckbox = document.getElementById('flexCheckIndeterminate');
parentCheckbox.addEventListener('change', e => {
    document.querySelectorAll('.form-check-input').forEach(checkbox => {
        checkbox.checked = e.target.checked
    })
});
    
document.querySelectorAll('tbody .form-check-input').forEach(checkbox => {
    checkbox.addEventListener('change', ()=> {
        var tbodyCheckbox = document.querySelectorAll('tbody .form-check-input').length;
        var tbodyCheckedbox = document.querySelectorAll('tbody .form-check-input:checked').length;
        if(tbodyCheckbox == tbodyCheckedbox){
            //console.log('All selected')
            parentCheckbox.indeterminate = false;
            parentCheckbox.checked = true;
        }
        if (tbodyCheckbox > tbodyCheckedbox && tbodyCheckedbox>=1) {
            // console.log('Some selected')
            parentCheckbox.indeterminate = true;
        }
        if(tbodyCheckedbox==0) {
            // console.log('No any selected')
            parentCheckbox.indeterminate = false;
            parentCheckbox.checked = false;
        }

    })
})
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="90f2ffffe4e3e4e2f1e0d0a5bea0bea2">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384- 
       EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5d7dadac1c6c1c7d4c5f5809b859b87">[email protected]</a>/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
        crossorigin="anonymous"></script>

<div class="container">
    <div class="row">
        <div class="col-sm-12 py-2">
            <h4>Bootstrap Table Checkbox (Unchecked/Indeterminate/Checked)</h4>
        </div>
        <div class="col-sm-12">
            <table class="table table-bordered table-hover" id="dataTable" width="100%" cellspacing="0">
                <thead>
                    <tr>
                        <th>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" value="" id="flexCheckIndeterminate">
                                <label class="form-check-label" for="flexCheckIndeterminate">
                                </label>
                            </div>
                        </th>
                        <th>#</th>
                        <th>Name</th>
                        <th>ID</th>
                        <th>Date & Time</th>
                        <th>Check-in</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" value="" id="defaultCheck1">
                                <label class="form-check-label" for="defaultCheck1">
                                </label>
                            </div>
                        </td>
                        <td>1</td>
                        <td>Raeesh</td>
                        <td>20421</td>
                        <td>03/11/2021 12:10</td>
                        <td>Yes</td>
                    </tr>
                    <tr>
                        <td>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" value="" id="defaultCheck2">
                                <label class="form-check-label" for="defaultCheck2">
                                </label>
                            </div>
                        </td>
                        <td>2</td>
                        <td>Alam</td>
                        <td>19091</td>
                        <td>02/11/2021 11:30</td>
                        <td>No</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

Answer №2

Why did you bring up JQuery when Bootstrap 5 no longer uses it? I find it curious.

Here is a possible solution:

// Access the main checkbox
 const checkbox = document.getElementById("flexCheckIndeterminate");

 // Listen for changes
 checkbox.addEventListener('input', evt => {
  // Get the checked value
  const checked = evt.target.checked;

  // Select all other checkboxes
  const checkboxes = document.querySelectorAll('input[type="checkbox"]');

  // Update all checkboxes with the main checkbox value
  checkboxes.forEach(checkbox => {
    checkbox.checked = checked;
  });
 });

Answer №3

Below is a sample demonstration:

document.getElementById('flexCheckIndeterminate').addEventListener('click', event => {
  document.querySelectorAll('.form-check-input').forEach(checkbox => {
    checkbox.checked = event.target.checked
  })
})
<!doctype HTML>
<html lang="en">

<head>
  <!-- Required meta tags -->
  <meta charset="utf-8>
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- Bootstrap CSS -->
  <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a8cac7c7dcdbdcdac9d8e89d8698869a">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384- 
       EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

  <title>Greetings, universe!</title>
</head>

<body>
  <h2>Bootstrap Table Checkbox Select All and Deselect</h2>
  <div class="container">
    <table class="table table-bordered table-hover" id="dataTable" width="100%" cellspacing="0">
      <thead>
        <tr>
          <th>
            <div class="form-check">
              <input class="form-check-input" type="checkbox" value="" id="flexCheckIndeterminate">
              <label class="form-check-label" for="flexCheckIndeterminate">                      
                    </label>
            </div>
          </th>
          <th>#</th>
          <th>Name</th>
          <th> ID</th>
          <th>Date & Time</th>
          <th>Check-in</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>
            <div class="form-check">
              <input class="form-check-input" type="checkbox" value="" id="defaultCheck1">
              <label class="form-check-label" for="defaultCheck1">                                                    
                  </label>
            </div>
          </td>
          <td>1</td>
          <td>Safaa</td>
          <td>20421</td>
          <td>12/2/2021 16:40</td>
          <td>Yes</td>
        </tr>

        <tr>
          <td>
            <div class="form-check">
              <input class="form-check-input" type="checkbox" value="" id="defaultCheck2">
              <label class="form-check-label" for="defaultCheck2">                                                    
                  </label>
            </div>
          </td>
          <td>2</td>
          <td>Noor</td>
          <td>19091</td>
          <td>15/2/2021 16:40</td>
          <td>No</td>
          </td>

        </tr>
      </tbody>
    </table>
  </div>


  <!-- Optional JavaScript; choose one of the two! -->

  <!-- Option 1: Bootstrap Bundle with Popper -->
  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4a2825253e393e382b3a0a7f647a6478">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

</body>

</html>

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

Get started with the free plan for sails.js on Paas

Looking to test out my sails.js application deployment options. Can't seem to find sails.js on the supported list for Heroku and OpenShift's node.js offerings. Are there any free Platform as a Service (PaaS) plans available for sails.js? ...

Upon refreshing the page, an inline script was not executed due to its violation of the Content Security Policy directive: "script-src 'self'"

When I refresh the page on my production build for all routes except "/", I encounter an error in my Node/React app which results in a blank page being displayed. The error message states: "Refused to execute inline script because it violates the followi ...

Unexpected result when trying to return a value from a recursive function

Attempting to solve the problem of calculating the number of ways a number can be decoded, with 1 as a, 3 as c, and 26 as z. The function seems to calculate the correct count, but for some reason only returns undefined. It appears that the recursive calls ...

The 'Component' you are trying to use cannot be rendered as a JSX component in Next.js

Take a look at the code in _app.tsx: function MyApp({ Component, pageProps }: AppProps) { return <Component {...pageProps} /> } An error is popping up during the project build process: Type error: 'Component' cannot be used as a JSX comp ...

Guide to setting up ajax to parse the text input and generate a table

Strange dilemma I've been grappling with for the past couple of days. Definitely a novice at this. Here's my code: $(document).ready(function() { var table = $('#table1').DataTable({ "ajax" : { url ...

Can someone guide me on the process of adding a personalized emoji to my discord bot?

After creating my own discord bot, I'm ready to take the next step and add custom emojis. While tutorials have helped me understand how to use client.cache to type an emoji, I'm unsure of how to upload them and obtain their ID for use in my bot. ...

Passing data from one component to another in Vue: A database perspective

I'm struggling to pass the id of a clicked button from MovieTable.vue to the WatchedForm.vue component. The WatchedForm.vue component is responsible for updating the data in the database based on the provided id, which corresponds to the Movie_id in t ...

Retrieving the value of the selected item when it is changed

I am currently using v-select/v-autocomplete in my project: <v-autocomplete v-modal="newRole" :items="roles" label="--Change role--" required return-object item-value="id" item-text=&qu ...

Leveraging React's UseEffect() to retrieve information from GraphQL

I am currently attempting to retrieve data from graphQL. I understand that by placing a function inside the react UseEffect(), I can trigger the function once the data is updated and structured. However, while working on a chatroom feature, I am facing an ...

Can someone guide me on passing functions from a service to the controller and invoking them using AngularJS ES6 syntax?

Whenever I attempt to invoke the getTodos function in the controller, it seems to be returning no value. I am trying to store the value returned by the getTodos() function into this.todos. However, this.todos keeps returning null. /* ----- todo/todo.ser ...

What is the best way to create space or add margins to a set of curved stacked images?

Below is the code I am currently using to arrange curved images side by side: <a-curvedimage v-for="(value, index) in model" :theta-start="setThumbThetaStart(thumb, index)" :theta-length="30"> // The thumb variable is not being utilized, only ...

Testing Redirects with Protractor and Jasmine: Strategies and Best Practices

Currently, I am in the process of creating a series of end-to-end tests using Protractor and Jasmine. I began by writing the following test: describe('app login page', function() { it('should be redirected to /#/login', function() { ...

What is the best way to extract a JSON object from a website search using getJSON or similar techniques?

Can anyone provide guidance on utilizing .getJSON() to access JSON-encoded information from a website that is being searched? I've implemented a Google Custom Search API for my site with the aim of retrieving the JSON file from the search results. Fo ...

Is it possible for me to include additional fields in a vuetify calendar event?

Is there a method to incorporate additional fields, such as a description, in addition to the name and start/end time for an event on the v-calendar's day view? ...

Canvg | Is there a way to customize canvas elements while converting from SVG?

Recently, I encountered an issue with styling SVG graphics dynamically generated from data. The SVG graphic appears like this: https://i.sstatic.net/xvIpE.png To address the problem, I turned to Canvg in hopes of converting the SVG into an image or PDF us ...

Issues with Bootstrap 5 navbar-light and font style rendering on Edge browser

My website seems to be having compatibility issues with Microsoft Edge. While everything works fine on Chrome, the navbar classes "navbar-light" and "bg-light" do not apply properly in Edge, and the font style defaults. I am using Bootstrap 5 and webfonts ...

Tips for passing the indexes of an array within nested ngFor loops in Angular

I have a 2D grid in my component that is created using nested ngFor loops, and I want to make certain grid elements clickable under specific conditions so they can call a function. Is there a way for me to pass the index of the clicked array element to the ...

Is there a way to streamline this function call that appears to be redundantly repeating the same actions?

I have developed a function to search for blog posts, prioritizing titles over excerpts and excerpts over content when added to the containsQuery array. While the code seems to be working well, I have noticed that there is a lot of redundant code. How can ...

Having trouble resolving "react-native-screens" from "node_modules eact-navigation-stacklibmoduleviewsStackViewStackViewCard.js"? Here's how to fix it

Here is the command I used for setting up react app routes: npm i react-native-router-flux --save After restarting npm with "npm start," I encountered this error message: Unable to resolve "react-native-screens" from "node_modules\react-navigation- ...

problem with making ajax requests during the server-side processing of DataTables

Currently tackling server-side processing with datatables, but encountering an ajax error that I'll detail shortly. First things first, here's my code: Table <table id="call_analysis_basic_table" class="display" cellspacing="0" width="100%"& ...