Javascript or Jquery to check and uncheck all checkbox

前端 未结 6 2034
忘了有多久
忘了有多久 2020-12-21 04:41

I have a form with a list of checkboxs. I want to create a checkAll and UncheckAll boxes for better user experience. I tried a lot of code that I got from Internet, but none

相关标签:
6条回答
  • 2020-12-21 05:22

    Javascript function to toggle (check/uncheck) all checkbox.

    function checkAll(bx)
    {
     var cbs = document.getElementsByTagName('input');
     for(var i=0; i < cbs.length; i++)
     {
        if(cbs[i].type == 'checkbox')
        {
            cbs[i].checked = bx.checked;
         }
     }
    }
    
    0 讨论(0)
  • 2020-12-21 05:25

    I live on jQuery, so I grabbed some code from here to update your code without using jQuery: http://www.coderanch.com/t/120677/HTML-CSS-JavaScript/find-Checkboxes

    Here's a working solution: http://jsfiddle.net/nvAtF/1/

    Here's the same solution with jQuery: http://jsfiddle.net/nvAtF/2/

    Here's the code block:

    function toggleCheckboxes(flag) {    
        var form = document.getElementById('groupImportForm');
        var inputs = form.elements;
        if(!inputs){
            //console.log("no inputs found");
            return;
        }
        if(!inputs.length){
            //console.log("only one elements, forcing into an array");
            inputs = new Array(inputs);        
        }
    
        for (var i = 0; i < inputs.length; i++) {  
          //console.log("checking input");
          if (inputs[i].type == "checkbox") {  
            inputs[i].checked = flag;
          }  
        }  
    }
    
    0 讨论(0)
  • 2020-12-21 05:25

    Checking & unchecking all checkboxes is very simple in jQuery. It works like that:

    var all_checkboxes = jQuery(':checkbox'); // choose & store all checkboxes
    all_checkboxes.prop('checked', true); // check all of them
    all_checkboxes.prop('checked', false); // uncheck all of them
    

    Here is the demonstration: jsfiddle.net/53fbc/

    0 讨论(0)
  • 2020-12-21 05:25

    Here's an ES6 one-liner to uncheck all by classname:

    document.querySelectorAll('.classname').forEach((e)=>e.checked=false);

    0 讨论(0)
  • Try this:

    $('input:checkbox').attr('checked', true);
    

    for check all

    $('input:checkbox').attr('checked', false);
    

    for unchek all

    0 讨论(0)
  • 2020-12-21 05:33
    var form = document.getElementById('groupImportForm');
    var inputs = form.elements;
    var checkboxes = [];
    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].type == 'checkbox') {
            inputs[i].checked =true;
        }
    }
    

    Javascript version of the example

    Same thin using jQuery

    $(".uncheckAll']").click(function() {
       $('.inputs').attr('checked','checked'); //add the atrribute checked
       // $('.inputs').removeAttr("checked");     //remove the attribute checked
    });
    

    Working example of jQuery

    0 讨论(0)
提交回复
热议问题