I have a form with a list of checkboxs. I want to create a checkAll and UncheckAll boxes for better user experience. I tried a lot of code that I got from Internet, but none
function checkAll(bx)
{
var cbs = document.getElementsByTagName('input');
for(var i=0; i < cbs.length; i++)
{
if(cbs[i].type == 'checkbox')
{
cbs[i].checked = bx.checked;
}
}
}
I live on jQuery, so I grabbed some code from here to update your code without using jQuery: http://www.coderanch.com/t/120677/HTML-CSS-JavaScript/find-Checkboxes
Here's a working solution: http://jsfiddle.net/nvAtF/1/
Here's the same solution with jQuery: http://jsfiddle.net/nvAtF/2/
Here's the code block:
function toggleCheckboxes(flag) {
var form = document.getElementById('groupImportForm');
var inputs = form.elements;
if(!inputs){
//console.log("no inputs found");
return;
}
if(!inputs.length){
//console.log("only one elements, forcing into an array");
inputs = new Array(inputs);
}
for (var i = 0; i < inputs.length; i++) {
//console.log("checking input");
if (inputs[i].type == "checkbox") {
inputs[i].checked = flag;
}
}
}
Checking & unchecking all checkboxes is very simple in jQuery. It works like that:
var all_checkboxes = jQuery(':checkbox'); // choose & store all checkboxes
all_checkboxes.prop('checked', true); // check all of them
all_checkboxes.prop('checked', false); // uncheck all of them
Here is the demonstration: jsfiddle.net/53fbc/
Here's an ES6 one-liner to uncheck all by classname:
document.querySelectorAll('.classname').forEach((e)=>e.checked=false);
Try this:
$('input:checkbox').attr('checked', true);
for check all
$('input:checkbox').attr('checked', false);
for unchek all
var form = document.getElementById('groupImportForm');
var inputs = form.elements;
var checkboxes = [];
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == 'checkbox') {
inputs[i].checked =true;
}
}
Javascript version of the example
Same thin using jQuery
$(".uncheckAll']").click(function() {
$('.inputs').attr('checked','checked'); //add the atrribute checked
// $('.inputs').removeAttr("checked"); //remove the attribute checked
});
Working example of jQuery