3

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

6
  • can u create a jsfiddle for the above code Commented Oct 3, 2013 at 9:23
  • typo.. doc should be document. sorry. voting to close. Commented Oct 3, 2013 at 9:24
  • possible duplicate of How do I check a checkbox with jQuery or JavaScript? Commented Oct 3, 2013 at 9:24
  • Answer foudn by the OP itself. Commented Oct 3, 2013 at 9:25
  • 1
    FYI, your if statement can be replaced with just checked = !checked;. The ! character negates your checked variable. If checked was equal to true, !checked would equal false. Commented Oct 3, 2013 at 9:25

2 Answers 2

3

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/

Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

bad idea if the script is being run by an onclick event

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.