Javascript toggle checkbox

夙愿已清 提交于 2019-12-31 03:06:07

问题


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


回答1:


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/




回答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.



来源:https://stackoverflow.com/questions/19155423/javascript-toggle-checkbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!