Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
105
rated 0 times [  109] [ 4]  / answers: 1 / hits: 16719  / 11 Years ago, thu, october 3, 2013, 12:00:00

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


More From » html

 Answers
9

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/


[#75260] Wednesday, October 2, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
darleneh

Total Points: 231
Total Questions: 110
Total Answers: 94

Location: Spain
Member since Thu, Dec 23, 2021
2 Years ago
;