I'm interested in learning more about how to select or deselect all checkboxes

How can I uncheck the "all" checkbox when I uncheck another checkbox?


$('#All').click(function () {
    var status = $(this).is(":checked");
    if (status) {
        $.each($('input[name="checkbox"]'), function () {
            this.checked = true;
        })
        $('input[name="checkbox"]').attr("checked", "checked");

    } else {
        $('input[name="checkbox"]').removeAttr("checked");
        $.each($('input[name="checkbox"]:checked'), function () {
            this.checked = false;
        })
    }

})

https://i.sstatic.net/Nywei.png

Answer №1

Give this a try

$(".check-all").click(function() 
{
var element=this;
  $(".child-checkbox").each(function(){    
   $(this).prop("checked",$(element).prop("checked"))   ;
    });
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox"  class="check-all"/>Check All
<input type="checkbox" class="child-checkbox"/>Option One
<input type="checkbox"  class="child-checkbox"/>Option Two
<input type="checkbox"  class="child-checkbox"/>Option Three
<input type="checkbox"  class="child-checkbox"/>Option Four

Answer №2

In my experience, using

$('input[name="checkbox"]').attr("checked", "checked");
does not work to change all checkboxes to checked. It is better to use prop() instead of .attr().

 $('#All').click(function () {
        var status = $(this).is(":checked");        
        if (status) {
            $('input:checkbox').prop("checked", "checked");
        } else {
            $('input:checkbox').removeAttr("checked");
        }

    });

Answer №3

If you're using vanilla JavaScript:

document.getElementById('All').addEventListener('click', function(event) {
    var checkBoxes = document.querySelectorAll('input[name="checkBox"]');
    Array.from(checkBoxes).forEach(box => {
        box.checked = this.checked;
    });
});

Answer №4

Give this a try:
Here is the HTML code:

<input type="button" class="check" value="select all" />
<input type="checkbox" class="cb-element" /> Option 1
<input type="checkbox" class="cb-element" /> Option 2
<input type="checkbox" class="cb-element" /> Option 3

And here is the jQuery code:
$(document).ready(function(){
    $('.check:button').toggle(function(){
        $('input:checkbox').prop('checked', true);
        $(this).val('unselect all');
    }, function(){
        $('input:checkbox').prop('checked', false);
        $(this).val('select all');        
    });
});
Hopefully, this helps you out.

Answer №5

In order to achieve the desired outcome, you can follow the instructions below:

Check All:
('input[type="checkbox"]').prop("checked", "checked");

Uncheck All:
$('input[type="checkbox"]').removeAttr("checked");

$('#All').click(function() { var status = $(this).is(":checked"); if (status) { $('input[type="checkbox"]').prop("checked", "checked");

  } else {
    $('input[type="checkbox"]').removeAttr("checked");
  }
});

Visit this link for more information.

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 are the best ways to personalize the Ant Design table and pagination component?

Is there a way to customize and design table and pagination components? Specifically, I am looking to set the header color of the table as green. How can this be achieved? Similarly, for the pagination component, I want to have a background color on page n ...

AngularJS: Using $watch to retrieve the index of the modified item within an array

My current situation involves an array containing multiple objects. $scope.userCompetences = []; To monitor any changes in this array, I have implemented a deep watch: $scope.$watch('userCompetences', function (newVal, oldValue) { ...

Creating a hexagonal grid pattern with the use of texture

I have conducted several experiments in the past to determine the most effective way to create large-scale hexagon grids. I attempted drawing the hexagons using THREE.Line and THREE.LineSegments. While this method was successful for small grids, the perfo ...

Establish an HttpOnly cookie using JavaScript

Is it possible to convert a non-HttpOnly cookie into an HttpOnly cookie using JavaScript? ...

When attempting to open a link in a new tab, the ng-click function fails to execute

In Angular, utilizing both the <code>ng-click and ng-href directives at the same time will result in the click function being executed first. In this scenario, clicking on a link that navigates to Google will be prevented and instead an alert will be ...

What is the best way to display table rows for a specified date range?

I am working with a table and need to display only the rows that fall between two specific dates. <table id ="Table"> <thead> <tr> <th>Date</th> <th>Name</th> <th>Desc</th> </tr> </thead> ...

Prevent elements from displaying until Masonry has been properly set up

My goal is to merge Masonry elements with existing ones. Currently, the items appear before Masonry initializes then quickly adjust into position a moment later. I want them to remain hidden until they are in their proper place. This is the snippet (with ...

Merge two separate mongodb records

Just getting started with javascript / express / mongodb. For my initial project, I am working on a simple task manager where todos are categorized by priority - "high," "mid," or "low." However, I am facing an issue when trying to display different entri ...

Updating the variable in Angular 6 does not cause the view to refresh

I am facing an issue with my array variable that contains objects. Here is an example of how it looks: [{name: 'Name 1', price: '10$'}, {name: 'Name 2', price: '20$'}, ...] In my view, I have a list of products bei ...

Highcharts - Troubleshooting the chart reflow feature

Take a look at the fiddle I created. I encountered an issue with the chart width when toggling the sidebar. After seeking help on Stack Overflow from this post, I was able to solve it. Now, I'm facing another bug where adding transitions while togg ...

The target for ajaxSubmit is being duplicated instead of being replaced

I encountered a problem with the code below: $('#refresh').click(function () { alert($('.report-container').length); $('.report-container').each(function () { var accordian = this; var url = $(this) ...

Replace the current CSS styles of a pre-installed package

I recently added a package for a type writer effect, but I'm having trouble with it not overriding the CSS styles I've set in the component. Here's an example of what I have: <template> <v-row class="hero" align-content= ...

Guide to inserting text into an html element upon clicking an ASP:Button

In my code, there is a DIV that holds some text. Accompanying the text is an asp:Button. When this button is clicked, I aim to access and save this particular text. Nonetheless, it seems that once the button is clicked, the content of the DIV resets - lik ...

Popup window for Ajax pagination in CgridView

In my project, I am displaying a set of data in a pop-up window using cgridview. However, when I attempted to implement ajax pagination, it failed to work properly. To address this issue, I created a view called listInvoices that contains only the cgrid da ...

Error encountered in NEXT JS: Unable to parse URL from /api/projects or Error message: Failed to connect to 127.0.0.1:3000

Currently utilizing: export const getStaticProps = async () => { export const getStaticPaths = async () => { and accessing my API (pages/api/projects/) created with Next.js on my local host const res = await fetch("http://localhost:3000/api/ ...

Having trouble hiding the hamburger menu depending on the screen width

I'm trying to figure out how to hide the hamburger menu when the screen width exceeds 400px. You can check out the site at damf.co Currently, the hamburger menu appears when the screen width is less than 400px. If you click on it and then expand the ...

How to Add Motion to Several Markers

Exploring the concept of moving markers on a map with drawn polylines to simulate simultaneous movement is a fascinating challenge. However, encountering some difficulties, such as only the last marker moving while the others remain stationary, can be frus ...

What is the best way to make an array with values from a checkbox list?

I am working on a project that involves rendering a list of products categorized into different categories. Users can select these categories using checkboxes. Are you interested in learning how to create an array containing the selected values from the ch ...

How to Retrieve Information from an Array in VueJS

At the moment, the data being displayed on my page is an array, as shown in the snippet below: https://i.stack.imgur.com/zAvrc.png However, I only want to retrieve or display the project names. This is all I have at the moment: fetch(context,id){ ...

When making a jQuery AJAX call, the returned results may be displayed before the page headers, causing

I'm struggling to figure out why I keep encountering a parse error in my simple AJAX call using JSON. The resultText is displaying the full page source code instead of just the JSON response, showing "success" above the page headers. Below is the AJA ...