[removed] Unchecking all checkboxes

后端 未结 6 846
独厮守ぢ
独厮守ぢ 2021-01-18 07:42

I have problem dealing with unchecking all checkboxes. When I click on a toggle all checkbox, it could check all checkboxes. But if I uncheck the toggle all checkbox, nothin

相关标签:
6条回答
  • 2021-01-18 07:45

    You could also make it a Boolean Variable.

    <script>
    var isAllCheck = new Boolean(false);
    function togglecheckboxes(cn){
    
    var cbarray = document.getElementsByName(cn);
    for(var i = 0; i < cbarray.length; i++){
    
        if(isAllCheck){ //and then you could make this shorter.
            cbarray[i].checked = true;
            //alert( "it is false" );
        }else{ 
            cbarray[i].removeAttribute("checked");
            //alert( "it is true" );
        }
    }   
    isAllCheck = !isAllCheck;   
    }
    </script>
    
    0 讨论(0)
  • 2021-01-18 07:48

    Try this

        <script>
    var isAllCheck = false;
    function togglecheckboxes(master,cn){
    
        var cbarray = document.getElementsByName(cn);
        for(var i = 0; i < cbarray.length; i++){
    
            if( isAllCheck == false ){
                cbarray[i].checked = true;
                //alert( "it is false" );
            }else{ 
                cbarray[i].checked = false;
                //alert( "it is true" );
            }
    }   
    isAllCheck = !isAllCheck;   
    }
    </script>
    
    0 讨论(0)
  • 2021-01-18 07:53

    function uncheckElements()
    {
     var uncheck=document.getElementsByTagName('input');
     for(var i=0;i<uncheck.length;i++)
     {
      if(uncheck[i].type=='checkbox')
      {
       uncheck[i].checked=false;
      }
     }
    }

    0 讨论(0)
  • 2021-01-18 07:53

    You can do this with jQuery very easy and more understandable :)

    $('#mybutton').click(function(e) {
        $('.myCheckboxes').each(function(i,item){
            $(item).attr('checked', !$(item).is(':checked'));
        });
    });
    

    Try on jsFiddle

    0 讨论(0)
  • 2021-01-18 07:56

    The problem boils down to how you're setting the checked property of the checkox. You're assigning a string with "true" where you should be assigning the boolean value true.

    So to fix your code is easy:

    if( isAllCheck == false ){
        cbarray[i].checked = true;
    }else{ 
        cbarray[i].checked = false;
    }
    

    or, more succinctly

    cbarray[i].checked = !isAllCheck
    

    Live example: http://jsfiddle.net/SEJZP/

    0 讨论(0)
  • 2021-01-18 07:56

    After validating that isAllCheck is correct with your UI logic, you may do both with a simple vanilla-js one-liner

    Array.from(document.querySelectorAll('input[type=checkbox]').forEach(el => el.checked = isAllCheck);
    
    0 讨论(0)
提交回复
热议问题