Reputation: 718
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
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
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
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
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
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