How to implement "select all" check box in HTML?
Asked Answered
M

31

276

I have an HTML page with multiple checkboxes.

I need one more checkbox by the name "select all". When I select this checkbox all checkboxes in the HTML page must be selected. How can I do this?

Manhour answered 22/12, 2008 at 13:50 Comment(2)
If you want to degrade gracefully, selecting the "select all" should actually mean that all are selected regardless of their individual state. (visiting your page with javascript disabled)Equiprobable
In Firefox (and maybe others?) : Hit CTRL+SHIFT+K to open the console, then paste : $("input:checkbox").attr('checked', true) and hit Enter. All check-boxes on current page should now be checked. To un-check change True to False.Kersey
R
379
<script language="JavaScript">
function toggle(source) {
  checkboxes = document.getElementsByName('foo');
  for(var checkbox in checkboxes)
    checkbox.checked = source.checked;
}
</script>

<input type="checkbox" onClick="toggle(this)" /> Toggle All<br/>

<input type="checkbox" name="foo" value="bar1"> Bar 1<br/>
<input type="checkbox" name="foo" value="bar2"> Bar 2<br/>
<input type="checkbox" name="foo" value="bar3"> Bar 3<br/>
<input type="checkbox" name="foo" value="bar4"> Bar 4<br/>

UPDATE:

The for each...in construct doesn't seem to work, at least in this case, in Safari 5 or Chrome 5. This code should work in all browsers:

function toggle(source) {
  checkboxes = document.getElementsByName('foo');
  for(var i=0, n=checkboxes.length;i<n;i++) {
    checkboxes[i].checked = source.checked;
  }
}
Rhiannonrhianon answered 22/12, 2008 at 14:1 Comment(18)
for each(var checkbox in checkboxes) --------------------------------------- should: for(var checkbox in checkboxes)Goya
@HelloWorld: for each...in is actually valid Javascript: developer.mozilla.org/en/Core_JavaScript_1.5_Reference/… But, as porneL has pointed out, it's an obscure construct. Also, this code doesn't work in Safari 5 or Chrome 5. It works in FF 3.6, and IIRC, it worked in Safari 4. for(var i in checkboxes) checkboxes[i].checked = source.checked works in all browsers.Morganstein
If adopting this for jquery, remember that the source variable becomes an EventHandler class, for click events, so you need to specify the target object for the checked command to work. See my answer below.Blackandblue
@CanBerkGüder What if you wanted the check all boxes on one page? One check all to control one set of checkboxes and another check all to control another set.Velamen
Never use for in with a collection or arrayBrill
I was having a problem using this code. For me I had to change the function name.Logogram
for a complete answer, i am wondering how you would uncheck the "Toggle All" checkbox in the case where: (1) Toggle All is checked; (2) any of checkboxes where name="foo" is then unchecked?Hathaway
Why do you do , n=checkboxes.length;i<n instead of just i < checkboxes.length? Anyway, to make the function generic (code reuse), pass an additional parameter: (source, checkboxes_name) and do document.getElementsByName(checkboxes_name); It's better than hard-coding the name and making the function specific to a particular set of checkboxes.Betti
All checkboxes have the same name? How can you tell them from one another after the form is posted?Beaudoin
@Brill is there any sound reasoning behind your recommendation or is that just preference?Gyatt
@Gyatt for example: #501004Brill
@Betti It is good practice to set a variable to the length of the array to stop the chance for an infinite loop. If somewhere in your loop you add another checkbox the loop would never end as the length is always increasing.Odessaodetta
Always Declare Local VariablesDiminutive
Alright, as my edit was rejected for some reason, I guess I'll comment here. The for-each construct is deprecated and will not work! You have to use its replacement: for(let checkbox of checkboxes).Outstay
I'd just like to point out that having multiple checkboxes with the same name is invalid html. It serves the purpose of demonstrating the functionality here, but this being a very popular question, it'd be wise (for the sake of inexperienced future readers) to use a different selector (e.g. to assign a class to all the checkboxes we wish to handle this way).Eavesdrop
function toggle(source) { Array.from(document.getElementsByName(source.name)) .filter(checkbox => checkbox !== source) .forEach(checkbox => checkbox.checked = source.checked); } then put the name for the toggle checkbox the same as for other checkboxes, and then no need to hardcode the name inside the function. What about a function like this?Alternator
@Eavesdrop No, multiple names is perfectly OK and valid. This sets it apart from id.Toneytong
@Toneytong OK, maybe purely by the HTML standard it is valid (you would need identical names for e.g. a radio button); however, in this case it will not be functional HTML. When you submit such a form, you will only receive the value of the last checked box with that name.Eavesdrop
R
161

Using jQuery:

// Listen for click on toggle checkbox
$('#select-all').click(function(event) {   
    if(this.checked) {
        // Iterate each checkbox
        $(':checkbox').each(function() {
            this.checked = true;                        
        });
    } else {
        $(':checkbox').each(function() {
            this.checked = false;                       
        });
    }
}); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox-1" id="checkbox-1" />
<input type="checkbox" name="checkbox-2" id="checkbox-2" />
<input type="checkbox" name="checkbox-3" id="checkbox-3" />

<!-- select all boxes -->
<input type="checkbox" name="select-all" id="select-all" />
Revel answered 3/2, 2010 at 9:50 Comment(3)
i'd add an else clause to handle the deselect use case, ;-) .. else { // Iterate each checkbox $(":checkbox").each(function() { this.checked = false; }); }Atypical
If you want to leave out the if and else and still handle the deselect you can do it this way : var state = this.checked; $(':checkbox').each(function() { this.checked = state; });Ruhl
You may be able to simplify this to $(':checkbox').prop('checked', true); and $(':checkbox').prop('checked', false);Koller
I
97

I'm not sure anyone hasn't answered in this way (using jQuery):

  $( '#container .toggle-button' ).click( function () {
    $( '#container input[type="checkbox"]' ).prop('checked', this.checked)
  })

It's clean, has no loops or if/else clauses and works as a charm.

Included answered 12/3, 2013 at 1:31 Comment(1)
Slightly amending this to: $('#container').on('click', 'toggle-button', function () {...}) is more performant because jQuery only needs to listen for click events from within #container rather than the entire DOM. See more in the docs: api.jquery.com/onLetty
E
76

I'm surprised no one mentioned document.querySelectorAll(). Pure JavaScript solution, works in IE9+.

function toggle(source) {
    var checkboxes = document.querySelectorAll('input[type="checkbox"]');
    for (var i = 0; i < checkboxes.length; i++) {
        if (checkboxes[i] != source)
            checkboxes[i].checked = source.checked;
    }
}
<input type="checkbox" onclick="toggle(this);" />Check all?<br />

<input type="checkbox" />Bar 1<br />
<input type="checkbox" />Bar 2<br />
<input type="checkbox" />Bar 3<br />
<input type="checkbox" />Bar 4<br />
Electroballistics answered 5/2, 2016 at 6:58 Comment(3)
this worked in Chrome, but i had a lot of checkboxes for different reasons, so instead of targeting 'type="checkbox"', i targeted 'name="myobject"' and it also worked.Indite
Maybe this should be changed to the new correct answer, if not some discussion would be helpful. :-)Bes
This answer was a lot easier to implement into existing pages than the other answers. good job.Discontinuity
A
67

here's a different way less code

$(function () {
       $('#select-all').click(function (event) {
          
           var selected = this.checked;
           // Iterate each checkbox
           $(':checkbox').each(function () {    this.checked = selected; });

       });
    });
Acidulent answered 4/9, 2012 at 16:47 Comment(0)
K
16

Demo http://jsfiddle.net/H37cb/

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js" /></script>

<script type="text/javascript">
$(document).ready(function(){

$('input[name="all"],input[name="title"]').bind('click', function(){
var status = $(this).is(':checked');
$('input[type="checkbox"]', $(this).parent('li')).attr('checked', status);
});

});
</script>




<div id="wrapper">
 <li style="margin-top: 20px">
  <input type="checkbox" name="all" id="all" /> <label for='all'>All</label>
  <ul>
   <li><input type="checkbox" name="title" id="title_1" /> <label for="title_1"><strong>Title 01</strong></label>
    <ul>
     <li><input type="checkbox" name="selected[]" id="box_1" value="1" /> <label for="box_1">Sub Title 01</label></li>
     <li><input type="checkbox" name="selected[]" id="box_2" value="2" /> <label for="box_2">Sub Title 02</label></li>
     <li><input type="checkbox" name="selected[]" id="box_3" value="3" /> <label for="box_3">Sub Title 03</label></li>
     <li><input type="checkbox" name="selected[]" id="box_4" value="4" /> <label for="box_4">Sub Title 04</label></li>
    </ul>
   </li>
  </ul>
  <ul>
   <li><input type="checkbox" name="title" id="title_2" /> <label for="title_2"><strong>Title 02</strong></label>
    <ul>
     <li><input type="checkbox" name="selected[]" id="box_5" value="5" /> <label for="box_5">Sub Title 05</label></li>
     <li><input type="checkbox" name="selected[]" id="box_6" value="6" /> <label for="box_6">Sub Title 06</label></li>
     <li><input type="checkbox" name="selected[]" id="box_7" value="7" /> <label for="box_7">Sub Title 07</label></li>
    </ul>
   </li>
  </ul>
 </li>
</div>
Kragh answered 18/9, 2012 at 14:48 Comment(3)
For me it's only working for a single cycle.It toggles only once then it does nothing.Cherlycherlyn
So it's the attr() method I guess. changed it to prop()Cherlycherlyn
Well, if I deselect any item from the list shouldn't be the Select All checkbox deselected too?Shed
S
13

When you call document.getElementsByName("name"), you will get a Object. Use .item(index) to traverse all items of a Object

HTML:

<input type="checkbox" onclick="for(c in document.getElementsByName('rfile')) document.getElementsByName('rfile').item(c).checked = this.checked">

<input type=​"checkbox" name=​"rfile" value=​"/​cgi-bin/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​includes/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​misc/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​modules/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​profiles/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​scripts/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​sites/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​stats/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​themes/​">​
Sessile answered 15/11, 2013 at 10:15 Comment(1)
if I need an if condition inside the onclick, how can I add it? ThanksPremature
D
10

Slightly changed version which checks and unchecks respectfully

$('#select-all').click(function(event) {
        var $that = $(this);
        $(':checkbox').each(function() {
            this.checked = $that.is(':checked');
        });
    });
Dramaturge answered 1/8, 2013 at 19:2 Comment(0)
B
10

My simple solution allows to selectively select/deselect all checkboxes in a given portion of the form, while using different names for each checkbox, so that they can be easily recognized after the form is POSTed.

Javascript:

function setAllCheckboxes(divId, sourceCheckbox) {
    divElement = document.getElementById(divId);
    inputElements = divElement.getElementsByTagName('input');
    for (i = 0; i < inputElements.length; i++) {
        if (inputElements[i].type != 'checkbox')
            continue;
        inputElements[i].checked = sourceCheckbox.checked;
    }
}

HTML example:

<p><input onClick="setAllCheckboxes('actors', this);" type="checkbox" />All of them</p>
<div id="actors">
    <p><input type="checkbox" name="kevin" />Spacey, Kevin</p>
    <p><input type="checkbox" name="colin" />Firth, Colin</p>
    <p><input type="checkbox" name="scarlett" />Johansson, Scarlett</p>
</div>

I hope you like it!

Beaudoin answered 5/5, 2016 at 16:15 Comment(0)
C
9
<html>

<head>
<script type="text/javascript">

    function do_this(){

        var checkboxes = document.getElementsByName('approve[]');
        var button = document.getElementById('toggle');

        if(button.value == 'select'){
            for (var i in checkboxes){
                checkboxes[i].checked = 'FALSE';
            }
            button.value = 'deselect'
        }else{
            for (var i in checkboxes){
                checkboxes[i].checked = '';
            }
            button.value = 'select';
        }
    }
</script>
</head>

<body>
<input type="checkbox" name="approve[]" value="1" />
<input type="checkbox" name="approve[]" value="2" />
<input type="checkbox" name="approve[]" value="3" />

<input type="button" id="toggle" value="select" onClick="do_this()" />
</body>

</html>
Catadromous answered 21/12, 2012 at 10:36 Comment(0)
W
9

Try this simple JQuery:

$('#select-all').click(function(event) {
  if (this.checked) {
    $(':checkbox').prop('checked', true);
  } else {
    $(':checkbox').prop('checked', false);
  }
});
Woodberry answered 20/3, 2015 at 7:50 Comment(1)
You can simplify that to $(':checkbox').prop('checked', this.checked), no need for the conditional.Electroballistics
A
9

It's rather simple:

const selectAllCheckboxes = () => {
  const checkboxes = document.querySelectorAll('input[type=checkbox]');
  checkboxes.forEach((cb) => { cb.checked = true; });
}
Armistead answered 21/1, 2022 at 3:10 Comment(0)
H
7

This sample works with native JavaScript where the checkbox variable name varies, i.e. not all "foo."

<!DOCTYPE html>
<html>
<body>

<p>Toggling checkboxes</p>
<script>
function getcheckboxes() {
    var node_list = document.getElementsByTagName('input');
    var checkboxes = [];
    for (var i = 0; i < node_list.length; i++) 
    {
        var node = node_list[i];
        if (node.getAttribute('type') == 'checkbox') 
        {
            checkboxes.push(node);
        }
    } 
    return checkboxes;
}
function toggle(source) {
    checkboxes = getcheckboxes();
    for (var i = 0 n = checkboxes.length; i < n; i++) 
    {
        checkboxes[i].checked = source.checked;
    }
}
</script>    

<input type="checkbox" name="foo1" value="bar1"> Bar 1<br/>
<input type="checkbox" name="foo2" value="bar2"> Bar 2<br/>
<input type="checkbox" name="foo3" value="bar3"> Bar 3<br/>
<input type="checkbox" name="foo4" value="bar4"> Bar 4<br/>

<input type="checkbox" onClick="toggle(this)" /> Toggle All<br/>

</body>
</html>
Hemocyte answered 15/4, 2016 at 2:24 Comment(1)
your getcheckboxes function could be replaced with document.querySelectorAll('input[type=checkbox]');Helladic
H
6

JavaScript is your best bet. The link below gives an example using buttons to de/select all. You could try to adapt it to use a check box, just use you 'select all' check box' onClick attribute.

Javascript Function to Check or Uncheck all Checkboxes

This page has a simpler example

http://www.htmlcodetutorial.com/forms/_INPUT_onClick.html

Haul answered 22/12, 2008 at 13:56 Comment(0)
B
5

If adopting the top answer for jQuery, remember that the object passed to the click function is an EventHandler, not the original checkbox object. Therefore code should be modified as follows.

HTML

<input type="checkbox" name="selectThemAll"/> Toggle All<br/>

<input type="checkbox" name="foo" value="bar1"> Bar 1<br/>
<input type="checkbox" name="foo" value="bar2"> Bar 2<br/>
<input type="checkbox" name="foo" value="bar3"> Bar 3<br/>
<input type="checkbox" name="foo" value="bar4"> Bar 4<br/>

Javascript

$(function() {
    jQuery("[name=selectThemAll]").click(function(source) { 
        checkboxes = jQuery("[name=foo]");
        for(var i in checkboxes){
            checkboxes[i].checked = source.target.checked;
        }
    });
})
Blackandblue answered 6/7, 2011 at 11:45 Comment(1)
not only is the first input type wrong, but even after correcting it this did not work for meDynamotor
C
4
<asp:CheckBox ID="CheckBox1" runat="server" Text="Select All" onclick="checkAll(this);" />
<br />
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
    <asp:ListItem Value="Item 1">Item 1</asp:ListItem>
    <asp:ListItem Value="Item 2">Item 2</asp:ListItem>
    <asp:ListItem Value="Item 3">Item 3</asp:ListItem>
    <asp:ListItem Value="Item 4">Item 4</asp:ListItem>
    <asp:ListItem Value="Item 5">Item 5</asp:ListItem>
    <asp:ListItem Value="Item 6">Item 6</asp:ListItem>
</asp:CheckBoxList>

<script type="text/javascript">
    function checkAll(obj1) {
        var checkboxCollection = document.getElementById('<%=CheckBoxList1.ClientID %>').getElementsByTagName('input');

        for (var i = 0; i < checkboxCollection.length; i++) {
            if (checkboxCollection[i].type.toString().toLowerCase() == "checkbox") {
                checkboxCollection[i].checked = obj1.checked;
            }
        }
    }
</script>
Channa answered 9/5, 2012 at 11:3 Comment(0)
E
4

that should do the job done:

    $(':checkbox').each(function() {
        this.checked = true;                        
    });
Ericerica answered 26/2, 2013 at 15:11 Comment(0)
C
4

As I cannot comment, here as answer: I would write Can Berk Güder's solution in a more general way, so you may reuse the function for other checkboxes

<script type="text/javascript">
  function toggleCheckboxes(source, cbName) {
    checkboxes = document.getElementsByName(cbName);
    for (var i = 0, n = checkboxes.length; i < n; i++) {
      checkboxes[i].checked = source.checked;
    }
  }
</script>
<input type="checkbox" onClick="toggleCheckboxes(this,\'foo\')" /> Toggle All<br/>

<input type="checkbox" name="foo" value="bar1"> Bar 1<br/>
<input type="checkbox" name="foo" value="bar2"> Bar 2<br/>
<input type="checkbox" name="foo" value="bar3"> Bar 3<br/>
<input type="checkbox" name="foo" value="bar4"> Bar 4<br/>
<input type="checkbox" name="foo" value="bar5"> Bar 5<br/>
Cierracig answered 22/3, 2019 at 12:38 Comment(3)
Thanks khaldi and Clarity for pointing out the missing bracket!Cierracig
The language attribute on script elements was deprecated long ago. If you must add an attribute (and there is no requirement to do so), use the type attribute with the appropriate MIME type. See also HTML Script tag: type or language (or omit both)?Kroo
Ok, thank you Heretic Monkey! I updated the code.Cierracig
M
3

You may have different sets of checkboxes on the same form. Here is a solution that selects/unselects checkboxes by class name, using vanilla javascript function document.getElementsByClassName

The Select All button

<input type='checkbox' id='select_all_invoices' onclick="selectAll()"> Select All

Some of the checkboxes to select

<input type='checkbox' class='check_invoice' id='check_123' name='check_123' value='321' />
<input type='checkbox' class='check_invoice' id='check_456' name='check_456' value='852' />

The javascript

    function selectAll() {
        var blnChecked = document.getElementById("select_all_invoices").checked;
        var check_invoices = document.getElementsByClassName("check_invoice");
        var intLength = check_invoices.length;
        for(var i = 0; i < intLength; i++) {
            var check_invoice = check_invoices[i];
            check_invoice.checked = blnChecked;
        }
    }
Messeigneurs answered 12/10, 2017 at 20:21 Comment(1)
It does work. Please check out codepen.io/kustomweb/pen/gZqwLVMesseigneurs
M
3

This is what this will do, for instance if you have 5 checkboxes, and you click check all,it check all, now if you uncheck all the checkbox probably by clicking each 5 checkboxs, by the time you uncheck the last checkbox, the select all checkbox also gets unchecked

$("#select-all").change(function(){
   $(".allcheckbox").prop("checked", $(this).prop("checked"))
  })
  $(".allcheckbox").change(function(){
      if($(this).prop("checked") == false){
          $("#select-all").prop("checked", false)
      }
      if($(".allcheckbox:checked").length == $(".allcheckbox").length){
          $("#select-all").prop("checked", true)
      }
  })
Michalemichalski answered 19/7, 2018 at 6:59 Comment(1)
The .prop() solved my problem... .attr() or .checked = didn't :/Ardenardency
D
2
$(document).ready(function() {
                $(document).on(' change', 'input[name="check_all"]', function() {
                    $('.cb').prop("checked", this.checked);
                });
            });
Duvetyn answered 9/11, 2014 at 10:28 Comment(0)
P
2

Using jQuery and knockout:

With this binding main checkbox stays in sync with underliying checkboxes, it will be unchecked unless all checkboxes checked.

ko.bindingHandlers.allChecked = {
  init: function (element, valueAccessor) {
    var selector = valueAccessor();

    function getChecked () {
      element.checked = $(selector).toArray().every(function (checkbox) {
        return checkbox.checked;
      });
    }

    function setChecked (value) {
      $(selector).toArray().forEach(function (checkbox) {
        if (checkbox.checked !== value) {
          checkbox.click();
        }
      });
    }

    ko.utils.registerEventHandler(element, 'click', function (event) {
      setChecked(event.target.checked);
    });

    $(window.document).on('change', selector, getChecked);

    ko.utils.domNodeDisposal.addDisposeCallback(element, () => {
      $(window.document).off('change', selector, getChecked);
    });

    getChecked();
  }
};

in html:

<input id="check-all-values" type="checkbox" data-bind="allChecked: '.checkValue'"/>
<input id="check-1" type="checkbox" class="checkValue"/>
<input id="check-2" type="checkbox" class="checkValue"/>
Pamphlet answered 31/8, 2015 at 17:45 Comment(2)
I don't know enough about knockout (I am using ko3.4 from cdnjs.cloudflare.com but the above seems not to work - at all. I can set a breakpoint on the initial init: call which gets triggered when the page loads( which I assume is correct), but stepping into this yields nothing - none of the rest of the function is executed. Setting breakpoint on the other functions, and they never get triggered.Designed
Tony Suffolk, there art two event handlers set: onclick and onchange for checkbox, and checkbox value is updated at the end of the code. If this code does not work in your project, check data-bind attribute for checkbox.Pamphlet
T
2

to make it in short-hand version by using jQuery

The select all checkbox

<input type="checkbox" id="chkSelectAll">

The children checkbox

<input type="checkbox" class="chkDel">
<input type="checkbox" class="chkDel">
<input type="checkbox" class="chkDel">

jQuery

$("#chkSelectAll").on('click', function(){
     this.checked ? $(".chkDel").prop("checked",true) : $(".chkDel").prop("checked",false);  
})
Titian answered 26/4, 2018 at 15:48 Comment(0)
A
2

Below methods are very Easy to understand and you can implement existing forms in minutes

With Jquery,

$(document).ready(function() {
  $('#check-all').click(function(){
    $("input:checkbox").attr('checked', true);
  });
  $('#uncheck-all').click(function(){
    $("input:checkbox").attr('checked', false);
  });
});

in HTML form put below buttons

<a id="check-all" href="javascript:void(0);">check all</a>
<a id="uncheck-all" href="javascript:void(0);">uncheck all</a> 

With just using javascript,

<script type="text/javascript">
function checkAll(formname, checktoggle)
{
  var checkboxes = new Array(); 
  checkboxes = document[formname].getElementsByTagName('input');

  for (var i=0; i<checkboxes.length; i++)  {
    if (checkboxes[i].type == 'checkbox')   {
      checkboxes[i].checked = checktoggle;
    }
  }
}
</script>

in HTML form put below buttons

<button onclick="javascript:checkAll('form3', true);" href="javascript:void();">check all</button>

<button onclick="javascript:checkAll('form3', false);" href="javascript:void();">uncheck all</button>

Angeles answered 2/3, 2020 at 16:3 Comment(0)
E
2

You can Use This code.

var checkbox = document.getElementById("dlCheckAll4Delete");
checkbox.addEventListener("click", function (event) {
  let checkboxes = document.querySelectorAll(".dlMultiDelete");
  checkboxes.forEach(function (ele) {
    ele.checked = !!checkbox.checked;
  });
});
Exciter answered 14/2, 2021 at 21:4 Comment(1)
elegant, and still relevant ;)Epiphenomenalism
D
1

Here is a backbone.js implementation:

events: {
    "click #toggleChecked" : "toggleChecked"
},
toggleChecked: function(event) {

    var checkboxes = document.getElementsByName('options');
    for(var i=0; i<checkboxes.length; i++) {
        checkboxes[i].checked = event.currentTarget.checked;
    }

},
Diminutive answered 12/9, 2016 at 5:52 Comment(0)
B
1

html

<input class='all' type='checkbox'> All
<input class='item' type='checkbox' value='1'> 1
<input class='item' type='checkbox' value='2'> 2
<input class='item' type='checkbox' value='3'> 3

javascript

$(':checkbox.all').change(function(){
  $(':checkbox.item').prop('checked', this.checked);
});
Bunyabunya answered 14/2, 2017 at 16:58 Comment(0)
P
1

1: Add the onchange event Handler

<th><INPUT type="checkbox" onchange="checkAll(this)" name="chk[]" /> </th>

2: Modify the code to handle checked/unchecked

 function checkAll(ele) {
     var checkboxes = document.getElementsByTagName('input');
     if (ele.checked) {
         for (var i = 0; i < checkboxes.length; i++) {
             if (checkboxes[i].type == 'checkbox') {
                 checkboxes[i].checked = true;
             }
         }
     } else {
         for (var i = 0; i < checkboxes.length; i++) {
             console.log(i)
             if (checkboxes[i].type == 'checkbox') {
                 checkboxes[i].checked = false;
             }
         }
     }
 }
Petcock answered 20/3, 2017 at 11:39 Comment(1)
Please do not copy paste code, instead refer with a link #19282719Sememe
A
0

You can use this simple code

$('.checkall').click(function(){
    var checked = $(this).prop('checked');
    $('.checkme').prop('checked', checked);
});
Antelope answered 9/11, 2017 at 17:10 Comment(0)
R
0

Maybe a bit late, but when dealing with a check all checkbox, I believe you should also handle the scenario for when you have the check all checkbox checked, and then unchecking one of the checkboxes below.

In that case it should automatically uncheck the check all checkbox.

Also when manually checking all the checkboxes, you should end up with the check all checkbox being automatically checked.

You need two event handlers, one for the check all box, and one for when clicking any of the single boxes below.

// HANDLES THE INDIVIDUAL CHECKBOX CLICKS
function client_onclick() {
    var selectAllChecked = $("#chk-clients-all").prop("checked");

    // IF CHECK ALL IS CHECKED, AND YOU'RE UNCHECKING AN INDIVIDUAL BOX, JUST UNCHECK THE CHECK ALL CHECKBOX.
    if (selectAllChecked && $(this).prop("checked") == false) {
        $("#chk-clients-all").prop("checked", false);
    } else { // OTHERWISE WE NEED TO LOOP THROUGH INDIVIDUAL CHECKBOXES AND SEE IF THEY ARE ALL CHECKED, THEN CHECK THE SELECT ALL CHECKBOX ACCORDINGLY.
        var allChecked = true;
        $(".client").each(function () {
            allChecked = $(this).prop("checked");
            if (!allChecked) {
                return false;
            }
        });
        $("#chk-clients-all").prop("checked", allChecked);
    }
}

// HANDLES THE TOP CHECK ALL CHECKBOX
function client_all_onclick() {
    $(".client").prop("checked", $(this).prop("checked"));
}
Reversal answered 14/6, 2018 at 20:42 Comment(0)
C
-2

Simple and to the POINT:

jQuery - Upon Clicking a button or div or a label element. Check off all checkboxes on the page. Keep in mind you'll have to adjust :checkbox to make it more specific.

jQuery("#My-Button").click(function() {

  jQuery(':checkbox').each(function() {
    if(this.checked == true) {
      this.checked = false;                        
    } else {
      this.checked = true;                        
    }      
  });

});
Circulation answered 6/10, 2016 at 14:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.