Count the number of checked checkboxes in HTML

后端 未结 6 874
一整个雨季
一整个雨季 2020-12-10 01:13

So basically i want to count the number of checkboxes that are ticked. I get my code to the point where it counts them successfully, but I want to put in an alert that shows

相关标签:
6条回答
  • 2020-12-10 01:38

    try this using jquery

    Method 1:

    alert($('.checkbox_class_here :checked').size());
    

    Method 2:

    alert($('input[name=checkbox_name]').attr('checked'));
    

    Method: 3

    alert($(":checkbox:checked").length);
    
    0 讨论(0)
  • 2020-12-10 01:38
    var checkboxes = document.getElementsByName("fruit");
    for(i = 0 ; i<checkboxes.length; i++)
    {
    if(checkboxes[i].checked==0){checkboxes.splice(i,1);}
    }
    alert("Number of checked checkboxes: "+checkboxes.length);
    
    0 讨论(0)
  • 2020-12-10 01:40

    The initial code was very nearly right. the line alert(count); was in the wrong place. It should have come after the second closing brace like this:-

     function checkboxes()
      {
       var inputElems = document.getElementsByTagName("input"),
        count = 0;
    
        for (var i=0; i<inputElems.length; i++) {       
           if (inputElems[i].type == "checkbox" && inputElems[i].checked == true){
              count++;
           }
        }
        alert(count);
     }
    

    In the wrong place it was giving you an alert message with every checked box.

    0 讨论(0)
  • 2020-12-10 01:42

    Try this code

     <br />Apples
                    <input type="checkbox" name="fruit" checked/>Oranges
                    <input type="checkbox" name="fruit" />Mango
                    <input type="checkbox" name="fruit" />
    
                    <br />Yes
    <input type="radio" name="yesorno" id="yes" onClick="checkboxes();" />
    

    Javascript

         function checkboxes()
          {
           var inputElems = document.getElementsByTagName("input"),
            count = 0;
    
            for (var i=0; i<inputElems.length; i++) {       
               if (inputElems[i].type == "checkbox" && inputElems[i].checked == true){
                  count++;
                  alert(count);
               }
    
            }
         }
    

    FIDDLE DEMO

    0 讨论(0)
  • 2020-12-10 01:47

    This should do the trick:

    alert(document.querySelectorAll('input[type="checkbox"]:checked').length);

    0 讨论(0)
  • 2020-12-10 01:47

    Thanks to Marlon Bernardes for this. alert(document.querySelectorAll('input[type="checkbox"]:checked').length);

    If you have more than one form with different checkbox names in each, the above code will count all checkboxes in all forms.

    To get over this, you can modify it to isolate by name.

    var le = document.querySelectorAll('input[name="chkboxes[]"]:checked').length;
    
    0 讨论(0)
提交回复
热议问题