Jquery make checkbox checked on other checkbox removal - javascript

I'm trying to make a filter to output some filtered results. The output goes to an array. I have four checkboxes. I was almost able to achieve the result I wanted. However, I want to make the All Levels checkbox checked again when there is no selections left. Here is what I have at the moment. I'm new to jquery so my code must be not efficient. If one can suggest or improve my code to achieve exact same result that would be great too! Thanks!
HTML
<div id="course-levels" class="list-group">
<input type="checkbox" value="all-levels" id="all-levels">
<input type="checkbox" value="degree" class="group">
<input type="checkbox" value="pgd" class="group">
<input type="checkbox" value="hnd" class="group">
</div>
Jquery
<script>
$(document).ready(function(){
// get reference to input elements
var inp = document.getElementsByTagName('input');
var levels = [];
// if checkboxes under 'group' class is not checked
if ($('input.group').prop('checked') == false) {
// make #all-levels default selected checkbox
$('#all-levels').prop('checked', true);
// make it readonly
$("#all-levels").attr('disabled', true);
// get other input values to levels array
for (var i=0; i < inp.length; i++) {
// skip default checkbox value
if (inp[i].value == 'all-levels') {
continue;
}
levels.push(inp[i].value);
}
console.log(levels);
}
// if user checked any other checkbox now
$('input.group').on('click', function () {
// remove check from default checkbox
$('#all-levels').prop('checked', false);
// make it enabled
$('#all-levels').removeAttr('disabled');
// get new values to levels array
levels = $('#course-levels input:checked').not($('#all-levels')).map(function () {
return this.value;
}).get();
console.log(levels);
}).eq(0).change();
// if all levels checkbox is clicked again
$('#all-levels').on('click', function(){
$('input.group').prop('checked', false);
// make default checkbox readonly so it will stay default
$('#all-levels').attr('disabled', true);
// make array empty
levels = [];
// get all input values to levels array
for (var i=0; i < inp.length; i++) {
// skip default checkbox value
if (inp[i].value == 'all-levels') {
continue;
}
levels.push(inp[i].value);
}
console.log(levels);
});
});
</script>

You can do this simply by checking if all the .group checkbox length is same as checked .group checkbox length or not and based on that make #all-levels selected again like:
$('#all-levels').prop('checked', $('input.group').length === $('input.group:checked').length);
$(document).ready(function() {
// get reference to input elements
var inp = document.getElementsByTagName('input');
var levels = [];
// if checkboxes under 'group' class is not checked
if ($('input.group').prop('checked') == false) {
// make #all-levels default selected checkbox
$('#all-levels').prop('checked', true);
// make it readonly
$("#all-levels").attr('disabled', true);
// get other input values to levels array
for (var i = 0; i < inp.length; i++) {
// skip default checkbox value
if (inp[i].value == 'all-levels') {
continue;
}
levels.push(inp[i].value);
}
console.log(levels);
}
// if user checked any other checkbox now
$('input.group').on('click', function() {
// remove check from default checkbox
$('#all-levels').prop('checked', false);
// make it enabled
$('#all-levels').removeAttr('disabled');
// get new values to levels array
levels = $('#course-levels input:checked').not($('#all-levels')).map(function() {
return this.value;
}).get();
//console.log(levels);
$('#all-levels').prop('checked', $('input.group').length === $('input.group:checked').length);
}).eq(0).change();
// if all levels checkbox is clicked again
$('#all-levels').on('click', function() {
$('input.group').prop('checked', false);
// make default checkbox readonly so it will stay default
$('#all-levels').attr('disabled', true);
// make array empty
levels = [];
// get all input values to levels array
for (var i = 0; i < inp.length; i++) {
// skip default checkbox value
if (inp[i].value == 'all-levels') {
continue;
}
levels.push(inp[i].value);
}
console.log(levels);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="course-levels" class="list-group">
<input type="checkbox" value="all-levels" id="all-levels">
<input type="checkbox" value="degree" class="group">
<input type="checkbox" value="pgd" class="group">
<input type="checkbox" value="hnd" class="group">
</div>

Related

How to keep a stored array of input checkbox value?

I have a input checkbox that act as a category filter. I want to store only those values of input checkboxes in an array that are checked in a var checkedAttr. Then do a test if any of the already existing values match any in the array and if it does delete it. The problem I'm having is that... when an input checkbox is clicked, it will store it as many times as the $each loop goes or input checkboxes there are, in this case (three times). I also noticed when unchecking more than one, then rechecking the same one, it will add the values as many times as the $each loop goes and will somehow bypass deleting from the array. I just want to simply add (checked values) / delete (unchecked values) from the array every time the user checks or unchecks.
Here's a jsfiddle.
HTML:
<div id="category-list">
<h1>Categories</h1>
<input class="categories" type="checkbox" name="filter" value="Math" checked>Math<br/>
<input class="categories" type="checkbox" name="filter" value="Science" checked>Science<br/>
<input class="categories" type="checkbox" name="filter" value="Reading" checked>Reading
</div>
jQuery:
var checkedAttr = []; // array for checked attributes
// change event listener for whenever one or more of the following checkboxes have been checked/unchecked
$('#category-list :checkbox').change(function()
{
var value = $(this).val();
if($(this).is(':checked')) // checked
{
console.log(value + ' is now checked!!!!!!!!!!!!!!!!!!!!!!!!');
$('#category-list :checkbox').each(function(i, item){ // loop thru the input checkboxes
if(!(value === $(item).val())) // check if the current value does NOT match that already stored in array
{
checkedAttr.push(value); // add value to array
console.log("checkedAttr:", checkedAttr);
}
else // if it does match...
{
checkedAttr.splice(i, 1);// remove it from array
console.log("checkedAttr:", checkedAttr);
}
});
// check which attributes are checked and store in 'checkedAttr' array
//$('input[name=filter]').each(function(i, item){
//});
}
else // unchecked
{
console.log(value + ' is now unchecked!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
}
});
Check it Brother its working as you want
var checkedAttr = [];
$('#category-list :checkbox').change(function()
{
checkedAttr = [];
$('#category-list :checkbox').each(function(i, item){
if($(item).is(':checked'))
{
checkedAttr.push($(item).val());
}
});
console.log("checkedAttr:", checkedAttr);
});
You can also check it in JSFiddle
https://jsfiddle.net/xdrLra77/
You can do it simply with a mapcall
var checkedAttr = [];
$('#category-list :checkbox').change(function() {
checkedAttr = $('#category-list :checked').map(function(){
return $(this).val();
}).get();
console.log(checkedAttr);
});
(Updated jFiddle)
(Edit: better yet, put the condition in the jQuery selector)
Edited
var checkedAttr = []; // array for checked attributes
//first load, see what is checked
$('#category-list :checkbox').each(function(){
if($(this).is(':checked')) // checked
checkedAttr.push($(this).val())
})
// change event listener for whenever one or more of the following checkboxes have been checked/unchecked
$('#category-list :checkbox').change(function()
{
var value = $(this).val();
var position = checkedAttr.indexOf($(this).val());
if($(this).is(':checked')) // checked
{
if(position == -1){ // dnot exist in array, add
checkedAttr.push($(this).val());
console.log("checkedAttr:", checkedAttr);
}else{ // exist in array, do nothing
//do nothing
}
console.log(value + ' is now checked!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
}
else // unchecked
{
if(position == -1){ // dont exist in array, do nothing
//do nothing
}else{ // exist in array, remove
checkedAttr.splice(position,1);
console.log("checkedAttr:", checkedAttr);
}
console.log(value + ' is now unchecked!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
}
});
You can get the checked elements by using $('.categories:checked'). Then you may iterate through those values to get the actual values
var checkedValues= $('.categories:checked');
var valuesArray=[];
$.each(checkedValues, function(checkedValue){
valuesArray.push(checkedValue.value)
}
Use $.inArray:
if (index === -1 && $(this).is(':checked')) {
checkedAttr.push(value); // add value to array
console.log("added:", checkedAttr);
} else if (index !== -1 && ! $(this).is(':checked')) {
checkedAttr.splice(index, 1);// remove it from array
console.log("removed:", checkedAttr);
}
Amended fiddle: https://jsfiddle.net/o1rmz1o1/4/

Validating a checkbox after already validating other sections of a form [duplicate]

I have a form with multiple checkboxes and I want to use JavaScript to make sure at least one is checked. This is what I have right now but no matter what is chosen an alert pops up.
JS (wrong)
function valthis(){
if (document.FC.c1.checked) {
alert ("thank you for checking a checkbox")
} else {
alert ("please check a checkbox")
}
}
HTML
<p>Please select at least one Checkbox</p>
<br>
<br>
<form name = "FC">
<input type = "checkbox" name = "c1" value = "c1"/> C1
<br>
<input type = "checkbox" name = "c1" value = "c2"/> C2
<br>
<input type = "checkbox" name = "c1" value = "c3"/> C3
<br>
<input type = "checkbox" name = "c1" value = "c4"/> C4
<br>
</form>
<br>
<br>
<input type = "button" value = "Edit and Report" onClick = "valthisform();">
So what I ended up doing in JS was this:
function valthisform(){
var chkd = document.FC.c1.checked || document.FC.c2.checked||document.FC.c3.checked|| document.FC.c4.checked
if (chkd == true){
} else {
alert ("please check a checkbox")
}
}
I decided to drop the "Thank you" part to fit in with the rest of the assignment. Thank you so much, every ones advice really helped out.
You should avoid having two checkboxes with the same name if you plan to reference them like document.FC.c1. If you have multiple checkboxes named c1 how will the browser know which you are referring to?
Here's a non-jQuery solution to check if any checkboxes on the page are checked.
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
var checkedOne = Array.prototype.slice.call(checkboxes).some(x => x.checked);
You need the Array.prototype.slice.call part to convert the NodeList returned by document.querySelectorAll into an array that you can call some on.
This should work:
function valthisform()
{
var checkboxs=document.getElementsByName("c1");
var okay=false;
for(var i=0,l=checkboxs.length;i<l;i++)
{
if(checkboxs[i].checked)
{
okay=true;
break;
}
}
if(okay)alert("Thank you for checking a checkbox");
else alert("Please check a checkbox");
}
If you have a question about the code, just comment.
I use l=checkboxs.length to improve the performance. See http://www.erichynds.com/javascript/javascript-loop-performance-caching-the-length-property-of-an-array/
I would opt for a more functional approach. Since ES6 we have been given such nice tools to solve our problems, so why not use them.
Let's begin with giving the checkboxes a class so we can round them up very nicely.
I prefer to use a class instead of input[type="checkbox"] because now the solution is more generic and can be used also when you have more groups of checkboxes in your document.
HTML
<input type="checkbox" class="checkbox" value=ck1 /> ck1<br />
<input type="checkbox" class="checkbox" value=ck2 /> ck2<br />
JavaScript
function atLeastOneCheckboxIsChecked(){
const checkboxes = Array.from(document.querySelectorAll(".checkbox"));
return checkboxes.reduce((acc, curr) => acc || curr.checked, false);
}
When called, the function will return false if no checkbox has been checked and true if one or both is.
It works as follows, the reducer function has two arguments, the accumulator (acc) and the current value (curr). For every iteration over the array, the reducer will return true if either the accumulator or the current value is true.
the return value of the previous iteration is the accumulator of the current iteration, therefore, if it ever is true, it will stay true until the end.
Check this.
You can't access form inputs via their name. Use document.getElements methods instead.
Vanilla JS:
var checkboxes = document.getElementsByClassName('activityCheckbox'); // puts all your checkboxes in a variable
function activitiesReset() {
var checkboxesChecked = function () { // if a checkbox is checked, function ends and returns true. If all checkboxes have been iterated through (which means they are all unchecked), returns false.
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
return true;
}
}
return false;
}
error[2].style.display = 'none'; // an array item specific to my project - it's a red label which says 'Please check a checkbox!'. Here its display is set to none, so the initial non-error label is visible instead.
if (submitCounter > 0 && checkboxesChecked() === false) { // if a form submit has been attempted, and if all checkboxes are unchecked
error[2].style.display = 'block'; // red error label is now visible.
}
}
for (var i=0; i<checkboxes.length; i++) { // whenever a checkbox is checked or unchecked, activitiesReset runs.
checkboxes[i].addEventListener('change', activitiesReset);
}
Explanation:
Once a form submit has been attempted, this will update your checkbox section's label to notify the user to check a checkbox if he/she hasn't yet. If no checkboxes are checked, a hidden 'error' label is revealed prompting the user to 'Please check a checkbox!'. If the user checks at least one checkbox, the red label is instantaneously hidden again, revealing the original label. If the user again un-checks all checkboxes, the red label returns in real-time. This is made possible by JavaScript's onchange event (written as .addEventListener('change', function(){});
You can check that atleast one checkbox is checked or not using this simple code. You can also drop your message.
Reference Link
<label class="control-label col-sm-4">Check Box 2</label>
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck1 /> ck1<br />
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck2 /> ck2<br />
<script>
function checkFormData() {
if (!$('input[name=checkbox2]:checked').length > 0) {
document.getElementById("errMessage").innerHTML = "Check Box 2 can not be null";
return false;
}
alert("Success");
return true;
}
</script>
< script type = "text/javascript" src = "js/jquery-1.6.4.min.js" > < / script >
< script type = "text/javascript" >
function checkSelectedAtleastOne(clsName) {
if (selectedValue == "select")
return false;
var i = 0;
$("." + clsName).each(function () {
if ($(this).is(':checked')) {
i = 1;
}
});
if (i == 0) {
alert("Please select atleast one users");
return false;
} else if (i == 1) {
return true;
}
return true;
}
$(document).ready(function () {
$('#chkSearchAll').click(function () {
var checked = $(this).is(':checked');
$('.clsChkSearch').each(function () {
var checkBox = $(this);
if (checked) {
checkBox.prop('checked', true);
} else {
checkBox.prop('checked', false);
}
});
});
//for select and deselect 'select all' check box when clicking individual check boxes
$(".clsChkSearch").click(function () {
var i = 0;
$(".clsChkSearch").each(function () {
if ($(this).is(':checked')) {}
else {
i = 1; //unchecked
}
});
if (i == 0) {
$("#chkSearchAll").attr("checked", true)
} else if (i == 1) {
$("#chkSearchAll").attr("checked", false)
}
});
});
< / script >
Prevent user from deselecting last checked checkbox.
jQuery (original answer).
$('input[type="checkbox"][name="chkBx"]').on('change',function(){
var getArrVal = $('input[type="checkbox"][name="chkBx"]:checked').map(function(){
return this.value;
}).toArray();
if(getArrVal.length){
//execute the code
$('#msg').html(getArrVal.toString());
} else {
$(this).prop("checked",true);
$('#msg').html("At least one value must be checked!");
return false;
}
});
UPDATED ANSWER 2019-05-31
Plain JS
let i,
el = document.querySelectorAll('input[type="checkbox"][name="chkBx"]'),
msg = document.getElementById('msg'),
onChange = function(ev){
ev.preventDefault();
let _this = this,
arrVal = Array.prototype.slice.call(
document.querySelectorAll('input[type="checkbox"][name="chkBx"]:checked'))
.map(function(cur){return cur.value});
if(arrVal.length){
msg.innerHTML = JSON.stringify(arrVal);
} else {
_this.checked=true;
msg.innerHTML = "At least one value must be checked!";
}
};
for(i=el.length;i--;){el[i].addEventListener('change',onChange,false);}
<label><input type="checkbox" name="chkBx" value="value1" checked> Value1</label>
<label><input type="checkbox" name="chkBx" value="value2"> Value2</label>
<label><input type="checkbox" name="chkBx" value="value3"> Value3</label>
<div id="msg"></div>
$('input:checkbox[type=checkbox]').on('change',function(){
if($('input:checkbox[type=checkbox]').is(":checked") == true){
$('.removedisable').removeClass('disabled');
}else{
$('.removedisable').addClass('disabled');
});
if(($("#checkboxid1").is(":checked")) || ($("#checkboxid2").is(":checked"))
|| ($("#checkboxid3").is(":checked"))) {
//Your Code here
}
You can use this code to verify that checkbox is checked at least one.
Thanks!!

How to hide the parent of an unchecked checkbox?

I have a set of random/dynamic generated div checkboxes:
<div>A1 <input type='checkbox' name='A[]' value='A1'> </div>
<div>A2 <input type='checkbox' name='A[]' value='A2'> </div>
<div>A3 <input type='checkbox' name='A[]' value='A3'> </div>
<div>B1 <input type='checkbox' name='B[]' value='B1'> </div>
<div>B2 <input type='checkbox' name='B[]' value='B2'> </div>
<div>C1 <input type='checkbox' name='C[]' value='C1'> </div>
What I am trying to do is when the user:
checks any A then the others will hide (entire div) but all A will still show.
unchecks a checkbox, then all A, B, C will show again.
This is because I am preventing the user from checking a mix of options.
PS:
You can provide a solution that might need me to modify the generated output of checkboxes.
try this fiddle
$("input[type=checkbox]").on("change", function() {
var thisName = $(this).attr("name");
if($(this).is(':checked')){
$(':checkbox').parent().hide();
$('input:checkbox[name|="'+thisName+'"]').parent().show();
} else {
$(':checkbox').parent().show();
}
});​
Try this one,
$('input:checkbox').click(function(){
if($(this).attr('checked') == 'checked'){
$('input:checkbox').parent('div').hide();
$('input:checkbox[name="'+$(this).attr('name')+'"]').parent('div').show();
}else{
if(!$('input:checkbox[checked="checked"]').length){
$('input:checkbox').parent('div').show();
}
}
})
​
Demo: http://jsfiddle.net/muthkum/uRd3e/3/
You can use some JQuery traversing to hide the non-matching elements:
// add the event handler
$("input[type=checkbox]").on("change", function() {
// get whether checked or unchecked
var checked = $(this).prop("checked") === true;
// get the name of the clicked element (eg, "A[]")
var thisName = $(this).prop("name");
// get the name of the clicked element (eg, "A[]")
var thisName = $(this).prop("name");
// get the grandparent element
$(this).parent().parent()
// get all the checkboxes
.find("input[type=checkbox]")
// filter to only the ones that don't match the current name
.filter(function(i, e) { return e.name != thisName; })
// hide or display them
.css("display", checked ? "none" : "");
});
you can simple do it like this
$('input[type=checkbox]').change(function () {
if ($(this).attr('checked')) {
var Name = $(this).prop("name");
$('div').filter(function(){
return $(this).find('input[type=checkbox]').prop("name") != Name;
}).hide();
}
else
{
$('input[type=checkbox]').attr('checked',false);
$('input[type=checkbox]').parent('div').show();
}
});​
Live Demo
Try code bellow:
$(":checkbox").click(function() {
var identifier = $(this).val().substring(0, 1);
$("input[type='checkbox']").each(function() {
if ($(this).val().indexOf(identifier) != -1) {
$(this).parent().show();
} else {
$(this).parent().hide();
}
});
if ($("input:checked").length == 0) {
$("input[type='checkbox']").parent().show();
}
});
You can try on jsFiddle
This will hide all other checkbox types when FIRST of a type is checked and show all the other checkbox types when ALL of the checked box type are unchecked:
$("input:checkbox").on("change", function() {
// get the name attribute
var nameAttr = $(this).prop("name");
// check how many checkbox inputs of that name attribute are checked
var checkedLength = $("input:checkbox[name=\"" + nameAttr + "\"]:checked").length;
// if 0, display other checkbox inputs, else if 1 hide all of the rest
if(checkedLength == 0) {
$("input:checkbox[name!=\"" + nameAttr + "\"]").parent().show();
}else if(checkedLength == 1) {
$("input:checkbox[name!=\"" + nameAttr + "\"]").parent().hide();
}
});
Overwhelmed by choice! Here's a plain JS version that just disables members of the non–selected groups.
I think that's better than hiding them so users can see the other options after they've selected one. Otherwise, to see the other options again, they must deselect all checkboxes in the group.
Note that div is a parent of the inputs, the listener passes a reference to the element and the related event object, modify as required.
<script>
function doStuff(div, evt) {
var checked, el, group, j, inputs, name, re;
var t = evt.target || evt.srcElement;
if (t.nodeName && t.nodeName.toLowerCase() == 'input' && t.type == 'checkbox') {
inputs = div.getElementsByTagName('input');
name = t.name;
// Set checked to true if any input with this name is checked
group = document.getElementsByName(name);
j = group.length;
while (j-- && !checked) {
checked = group[j].checked;
}
// Loop over inputs, hide or show depending on tests
for (var i=0, iLen=inputs.length; i<iLen; i++) {
el = inputs[i];
// If name doesn't match, disable
el.disabled = checked? (el.name != name) : false;
}
}
}
</script>
<div onclick="doStuff(this, event)">
<div>A1 <input type='checkbox' name='A[]' value='A1'></div>
<div>A2 <input type='checkbox' name='A[]' value='A2'></div>
<div>A3 <input type='checkbox' name='A[]' value='A3'></div>
<div>B1 <input type='checkbox' name='B[]' value='B1'></div>
<div>B2 <input type='checkbox' name='B[]' value='B2'></div>
<div>C1 <input type='checkbox' name='C[]' value='C1'></div>
</div>
Thanks guys, especially dbaseman (get me ideal) :
ok, Here is my code after referring from you all.
$("input[type=checkbox]").on("click", function() {
var sta = $(this).is(":checked"); sta=(sta==true?1:0);
if(sta==1){
var thisName = $(this).prop("name"); thisName=thisName.replace("[]","");
$("div input[type=checkbox]:not([name^=" + thisName + "])").parent().hide();
}else{
var num = $("[type=checkbox]:checked").length;
if(num==0){
$("div input[type=checkbox]").parent().show();
}
}
});
so far code able is performing as what i need.
Ps: i am still weak on jquery travelling part
Ps: Edited on re-opening all checkboxes part
Thanks once again!

too see if checkboxes have been checked javascript

Hallo
How would I go about in checking whether checkBox has been checked in javascript?
I C# it is simple enough
int selected = 0;
for (int loop = 0; loop < chkMeal.CheckedItems.Count; loop++)
{
selected++;
}
if (selected > 1)
{
MessageBox.Show("only one meal allowed", "Halt", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
How could I do a simlar thing with javascript?
kind regards
Arian
For instance, if you give your checkboxes a class you can do something like this:
var myboxes = document.getElementsByClassName('myboxes');
for (var i=0; i<myboxes.length;i++) {
if (myboxes[i].checked) {
alert('Box number '+i+' is checked!');
}
}
Simply put, give your form a unique id attribute. Then, traverse HTMLFormElement.elements and check against HTMLInputElement.checked for a truthy value.
HTML:
<form id="foo" method="post" action="./">
<input type="checkbox" name="check_a" value="foo" />
<input type="checkbox" name="check_b" value="bar" />
<input type="checkbox" name="check_c" value="baz" checked />
</form>
JS:
var foo = document.getElementById("foo"), i = 0, el;
for(i;i<foo.elements.length;i++)
{
el = foo.elements[i];
if(el.nodeType === 1 && el.tagName === "INPUT" && el.type === "checkbox")
{
//element node, is an input element, is a checkbox
if(el.checked)
{
//checkbox is checked
}
}
el = null;
}
Bonus reference:
HTMLFormElement (via DOM Level 2)
HTMLInputElement (via DOM Level 2)
Using a little bit of jQuery:
$(function() {
$('form').submit( function() {
if ($('[name="chkMeal"]:checked').length > 1) {
// show an error
return false; // cancel submit
}
});
});

Checkbox state with javascript

I have list of checkboxes in my jsp page.Based on Main checkbox i have to check/uncheck all child check boxes.
1)Take i have 10 child checkboxes and have main checkbox.When i check Main checkbox,i able to select all child checkboxes.if user unselect any child checkbox,i able to unselect
main checkbox.so here out of 10 childcheckboxes,i unselect 1 checkbox ,based on this i unchecked main checkbox.
But here my Question,if user checks that checkbox again,so here my status is selected all 10 checkboxes.So i should even checks the main checkbox too.
Add onclick handlers to the checkboxes.
Keep a count.
If it is checked add 1, if it becomes unchecked subtract one.
If the total equals the number of checkboxes, check the check all checkbox.
Here's a rough guide to how to do it:
<script type="text/javascript">
var checkboxCheck = (function() {
var boxes;
var mainCb;
// If all checkboxes checked, return true
function allChecked() {
var i = boxes.length;
while (i--) {
if (!boxes[i].checked) return false;
}
return true;
}
// If value is in array, return true
function oneOf(value, array) {
var i = array.length;
while(i--) {
if (array[i] == value) return true;
}
return false;
}
// Main function
return function(evt, el) {
// Get the element that was clicked on
var target = evt.target || evt.srcElement;
// Initialise boxes if not done already
if (!boxes) {
boxes = [];
var o = el.getElementsByTagName('input');
for (var i=o.length; --i;) {
if (o[i].type == 'checkbox') {
boxes.push(o[i]);
}
}
}
// Initialise mainCb if not done already
if (!mainCb) {
mainCb = document.getElementById('mainCb');
}
// If the click was on one of the checkboxes
if (oneOf(target, boxes)) {
// If they're all checked, check mainCb
// otherwise uncheck mainCb
mainCb.checked = allChecked(boxes);
// If the click was on mainCb
} else if (target == mainCb) {
// Set all checkboxes to same state as mainCb
for (var j=boxes.length; j--;) {
boxes[j].checked = mainCb.checked;
}
}
}
}())
</script>
<fieldset onclick="checkboxCheck(event, this)">
<label for="main">Check all<input type="checkbox" id="mainCb" value="0"></label>
<br>
<label for="cb0">0<input type="checkbox" id="cb0" value="0"></label>
<br>
<label for="cb1">1<input type="checkbox" id="cb1" value="1"></label>
<br>
<label for="cb2">2<input type="checkbox" id="cb2" value="2"></label>
</fieldset>

Categories

Resources