Reputation: 23409
I need to toggle all buttons with a single function. Function needs to toggle all checkboxes in the document as my checkboxes are freestanding and not part of a form.
I currently have this, but it is not working properly. I get syntax error: syntax error
in my firefox console.
checked=false;
function checkedAll() {
var c = new Array();
c = doc.getElementsByTagName('input');
if (checked == false){
checked = true;
}else{
checked = false;
}
for (var i = 0; i < c.length; i++){
if (c[i].type == 'checkbox'){
c[i].checked = checked;
}
}
}
How can I fix my code?
Thanks
Upvotes: 3
Views: 17176
Reputation: 145
You can alternatively perform the following for each checkbox element:
c[i].click();
This version will trigger any associated event handlers associated with that element.
Upvotes: 2
Reputation: 94499
Two main items to refactor. First, instead of doc
it must be document
. Second instead of relying on a global just pass in a boolean to determine whether or not to check the checkboxes.
function checkedAll(isChecked) {
var c = document.querySelectorAll('input[type="checkbox"]');
for (var i = 0; i < c.length; i++){
c[i].checked = isChecked;
}
}
JS Fiddle: http://jsfiddle.net/Jvnfm/107/
Upvotes: 3