How to count number of checkboxes selected


I'm trying to make a code that checks how many checkboxes are checked when clicking a button, as I'm making a system that duplicates records. I have a list with several checkboxes, and when the person clicks the "duplicate" button jQuery will check which ones are checked and get the value from them. I have no idea how to do it, because I tried in many ways and nothing. The last code I tried was this:


    $("#duplicar-registro").on('click', function(){

        var checkbox = $("#mcheckbox");

        for(i=0;i<= checkbox.length;i++){

            if($("input[id=mcheckbox]:checked") == true){

                console.log(i); //Ver no console

                console.log(i); //Ver no console também
asked by anonymous 11.07.2014 / 02:10

2 answers


To get the values of checkbox selected, you must first change the selector of your function. It is not allowed more than one element with the same id , so I suggest using the name of checkbox or a class for this, following example of implementation suggestion:


<label><input type="checkbox" value="1" name="mcheckbox[]" /> 1</label>
<label><input type="checkbox" value="2" name="mcheckbox[]" /> 2</label>
<label><input type="checkbox" value="3" name="mcheckbox[]" /> 3</label>
<label><input type="checkbox" value="4" name="mcheckbox[]" /> 4</label>
<label><input type="checkbox" value="5" name="mcheckbox[]" /> 5</label>
<button type="button" id="duplicar-registro">Duplicar Registro</button>


 $('#duplicar-registro').click(function () {
    //seletor para os checkbox com name mcheckbox selecionados
    var checkbox = $('input:checkbox[name^=mcheckbox]:checked');
    //verifica se existem checkbox selecionados
    if(checkbox.length > 0){
        //array para armazenar os valores
        var val = [];
        //função each para pegar os selecionados
        //exibe no console o array com os valores selecionados

Example: JSFiddle

11.07.2014 / 02:36

Example: Demo

<meta charset="utf-8">
<title>CheckBox Selecionados</title>
<script src="//"></script>
    <input type="checkbox" value="1" name="check1" id="check1">1<br>
    <input type="checkbox" value="2" name="check2" id="check2">2<br>
    <input type="checkbox" value="3" name="check3" id="check3">3<br>
    <input type="checkbox" value="4" name="check4" id="check4">4<br>
    <input type="button" value="Verificar" id="btnverificar" name="btnverificar">    
    <script type="text/javascript">
        $(document).ready(function(e) {
            $("#btnverificar").click(function(e) {
                $.each(($("input[type=checkbox]:checked")), function(index, obj){
11.07.2014 / 02:36