[javascript] Check/Uncheck all the checkboxes in a table

I have a table with information. The first column of the table have checkboxes. I can add/delete rows with a button by checking the checkboxes. The problem I have now is how do I select or deselect all the checkboxes using the checkbox on the header.

Here is my code:

<HTML>
  <HEAD>
    <TITLE> Add/Remove dynamic rows in HTML table </TITLE>
    <SCRIPT language="javascript">
      function addRow(tableID) {

        var table = document.getElementById(tableID);

        var rowCount = table.rows.length;
        var row = table.insertRow(rowCount);

        var cell1 = row.insertCell(0);
        var element1 = document.createElement("input");
        element1.type = "checkbox";
        element1.name="chkbox[]";
        cell1.appendChild(element1);

        var cell2 = row.insertCell(1);
        cell2.innerHTML = rowCount;

        var cell3 = row.insertCell(2);
        cell3.innerHTML = rowCount;

        var cell4 = row.insertCell(3);
        cell4.innerHTML = rowCount;

        var cell5 = row.insertCell(4);
        cell5.innerHTML = rowCount;

        var cell6 = row.insertCell(5);
        cell6.innerHTML = rowCount;
      }

      function deleteRow(tableID) {
        try {
        var table = document.getElementById(tableID);
        var rowCount = table.rows.length;

        for(var i=1; i<rowCount; i++) {
            var row = table.rows[i];
            var chkbox = row.cells[0].childNodes[0];
            if(null != chkbox && true == chkbox.checked) {
                table.deleteRow(i);
                rowCount--;
                i--;
            }
        }
        }catch(e) {
            alert(e);
        }
      }

      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>
  </HEAD>
  <BODY>

    <INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />

    <INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />

    <TABLE id="dataTable" border="1">
      <tr>
        <th><INPUT type="checkbox" name="chk[]"/></th>
        <th>Make</th>
        <th>Model</th>
        <th>Description</th>
        <th>Start Year</th>
        <th>End Year</th>
      </tr>
    </TABLE>
  </BODY>
</HTML>

This question is related to javascript html dom

The answer is


This solution is better because it is shorter and doesn't use a loop.

id="checkAll" is the header column

$('#checkAll').on('click', function() {
        if (this.checked == true)
            $('#userTable').find('input[name="checkboxRow"]').prop('checked', true);
        else
            $('#userTable').find('input[name="checkboxRow"]').prop('checked', false);
    });

All CheckBox Checked

$("input[type=checkbox]").prop('checked', true);


This will select and deselect all checkboxes:

function checkAll()
{
     var checkboxes = document.getElementsByTagName('input'), val = null;    
     for (var i = 0; i < checkboxes.length; i++)
     {
         if (checkboxes[i].type == 'checkbox')
         {
             if (val === null) val = checkboxes[i].checked;
             checkboxes[i].checked = val;
         }
     }
 }

Demo

Update:

You can use querySelectAll directly on the table to get the list of checkboxes instead of searching the whole document, but It might not be compatible with old browsers so you need to check that first:

 function checkAll()
 {
     var table = document.getElementById ('dataTable');
     var checkboxes = table.querySelectorAll ('input[type=checkbox]');
     var val = checkboxes[0].checked;
     for (var i = 0; i < checkboxes.length; i++) checkboxes[i].checked = val;
 }

Or to be more specific for the provided html structure in the OP question, this would be more efficient when selecting the checkboxes as it will access them directly instead of searching for them:

function checkAll (tableID)
{
    var table = document.getElementById (tableID);
    var val = table.rows[0].cells[0].children[0].checked;
    for (var i = 1; i < table.rows.length; i++)
    {
        table.rows[i].cells[0].children[0].checked = val;
    }
}

Demo


$(document).ready(function () {

            var someObj = {};

            $("#checkAll").click(function () {
                $('.chk').prop('checked', this.checked);
            });

            $(".chk").click(function () {

                $("#checkAll").prop('checked', ($('.chk:checked').length == $('.chk').length) ? true : false);
            });

            $("input:checkbox").change(function () {
                debugger;

                someObj.elementChecked = [];

                $("input:checkbox").each(function () {
                    if ($(this).is(":checked")) {
                        someObj.elementChecked.push($(this).attr("id"));

                    }

                });             
            });

            $("#button").click(function () {
                debugger;

                alert(someObj.elementChecked);

            });

        });
    </script>
</head>

<body>

    <ul class="chkAry">
        <li><input type="checkbox" id="checkAll" />Select All</li>

        <li><input class="chk" type="checkbox" id="Delhi">Delhi</li>

        <li><input class="chk" type="checkbox" id="Pune">Pune</li>

        <li><input class="chk" type="checkbox" id="Goa">Goa</li>

        <li><input class="chk" type="checkbox" id="Haryana">Haryana</li>

        <li><input class="chk" type="checkbox" id="Mohali">Mohali</li>

    </ul>
    <input type="button" id="button" value="Get" />

</body>

JSBin

Add onClick event to checkbox where you want, like below.

<input type="checkbox" onClick="selectall(this)"/>Select All<br/>
<input type="checkbox" name="foo" value="make">Make<br/>
<input type="checkbox" name="foo" value="model">Model<br/>
<input type="checkbox" name="foo" value="descr">Description<br/>
<input type="checkbox" name="foo" value="startYr">Start Year<br/>
<input type="checkbox" name="foo" value="endYr">End Year<br/>

In JavaScript you can write selectall function as

function selectall(source) {
  checkboxes = document.getElementsByName('foo');
  for(var i=0, n=checkboxes.length;i<n;i++) {
    checkboxes[i].checked = source.checked;
  }
}

Try this:

$("input[type=checkbox]").prop('checked', true).uniform();

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to dom

How do you set the document title in React? How to find if element with specific id exists or not Cannot read property 'style' of undefined -- Uncaught Type Error adding text to an existing text element in javascript via DOM Violation Long running JavaScript task took xx ms How to get `DOM Element` in Angular 2? Angular2, what is the correct way to disable an anchor element? React.js: How to append a component on click? Detect click outside React component DOM element to corresponding vue.js component