LGB
LGB

Reputation: 718

Negate checkbox selection status on multiple checkboxes

I have a big form with several checkboxes, having names chkbx0..chkbxN for them (N is known by PHP code which generates the form). I want to create a link-like entity which will invert the checked status (so, what was checked becomes unchecked and vice versa) for all the checkboxes when it's clicked. So basically I am interested in a javascript function which has a parameter (the "N") and does the work, and I would call it something like this:

    <p>You can reverse checkboxes <a href="javascript:chkbxsnegate(<?php echo $n; ?>);">by clicking here</a>.</p>

The checkboxes are something like these:

    <input type="checkbox" name="chkbx0">
    <input type="checkbox" name="chkbx1">
    ...

I use the parameter "N", because there can be more checkboxes, but I only need to invert checked status only till "N".

Please suggest me a javascript code fragment to implement function "chkbxsnegate". Thanks a lot in advance.

Upvotes: 2

Views: 4147

Answers (5)

KARASZI Istv&#225;n
KARASZI Istv&#225;n

Reputation: 31467

There is a shorter solution:

$('input[type="checkbox"]').each(function () {
  $(this).prop('checked', !$(this).is(':checked'));
});

Even shorter:

$("[type=checkbox]").each(function() {
    this.checked = !this.checked;
});

Upvotes: 4

Liam
Liam

Reputation: 29754

You can do it using Jquery

$('input[name^=chkbx]').each(function() {
  if ($(this).is(':checked'))
  {
     $(this).prop('checked', false);
  }
  else
  {
    $(this).prop('checked', true);
  }
});

Upvotes: 1

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123397

If I well understood you need to reverse the checked attribute until n^th element (from 0 to n^th included)

var chkbxsnegate = function(n) {
   var cbox = document.querySelectorAll('input[type="checkbox"][name^="chkbx"]');
   while (n--) {
      cbox[n].checked = !cbox[n].checked;
   }
}

Example fiddle: http://jsfiddle.net/wHPnA/

Upvotes: 0

Devator
Devator

Reputation: 3904

You should use jQuery to inverse the checkboxes.

$('a#cb-inverse').click(function() {
 $('input.my_cb').each(function() {
   $(this).is(':checked') ? $(this).removeAttr('checked') : $(this).attr('checked','checked');
 });
});

See this link for more information.

Upvotes: -1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324740

The following will work in most browsers, except IE7 and below (but it works in IE8 and 9)

function chkbxsnegate(n) {
    var qsa = document.querySelectorAll("input[type=checkbox][name=chkbx"+n+"]"),
        l = qsa.length, i;
    for( i=0; i<l; i++) qsa[i].checked = !qsa[i].checked;
}

Upvotes: 4

Related Questions