How to create a ‘select all’ checkbox in javascript

For HTML Code:

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

<input type='checkbox' name='ss' value='one'  />
<input type='checkbox' name='ss' value='two'  />
<input type='checkbox' name='ss' value='three'  />

We use Javascript:

<script>
  function toggle(source) {
    checkboxes = document.getElementsByName('ss');
    for (var i = 0, n = checkboxes.length; i < n; i++) {
      checkboxes[i].checked = source.checked;
    }
  }
</script>

I also came across this a bit later:

<script language="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>

and used with:

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

Ref: webdevdoor.com

You may also like...

Leave a Reply