Check all selected checkboxes

0

I want to validate that the user has to select all checkbox to insert something. I have validated that I select only one, but I can not get it all.

My code php :

while ($imprime = $resultado->fetch_assoc()) {
    $tabla .= '<tr>';
    $tabla .= '<td>' . $imprime["DESCRIPCION"] . '</td>';
    $tabla .= '<td><input class="checkRequi" name="checkRequi" type="checkbox" value=""></td>';         
    $tabla .= '</tr>';
}

In jQuery I check that it is selected:

$(document).ready(documentoListo);

function documentoListo () {
    $("#asigBen").click(compruebaChec)
}

function compruebaChec () {

    if ($("input[name=checkRequi]").is(":checked")) { //quiero que compruebe todos seleccionados

        alert("La política de privacidad ha sido aceptada");
        return true;

    } else {

        alert("Debe aceptar la política de privacidad");
        return false;

    }

}
    
asked by Kevin 08.06.2017 в 21:38
source

4 answers

3

You can compare if the length of the selection of all checkboxs matches the length of the checkboxs of that selection that are selected. Something like this:

var button = $("button");

button.on("click", function () {

  var checkboxs = $("input[name='checkRequi']");
  var todos = checkboxs.length === checkboxs.filter(":checked").length;
  
  console.log(todos ? "Están seleccionados todos" : "No has seleccionado todos los checkboxs");

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="checkRequi" />
<input type="checkbox" name="checkRequi" />
<input type="checkbox" name="checkRequi" />
<input type="checkbox" name="checkRequi" />
<input type="checkbox" name="checkRequi" />
<button>Comprueba</button>
    
answered by 08.06.2017 / 21:53
source
0

Here's how to do it with jQuery :

var estado = true;

$('input[type="checkbox"]').each(function () {
    var myCheck = $(this).prop('checked');
    if(!myCheck){
        estado = false;
    }
});

This way if one is not selected, the result will be FALSE , all must be selected so that the answer is TRUE .

    
answered by 08.06.2017 в 22:30
0

I hope this can help you. Scroll through checkboxs and validate if the number of checkboxes is equal to checkeds :

function compruebaChec () {

    var checked = 0;

    $('input[name=checkRequi]').each( function () {
        if($(this).is(':checked')){
            checked++;
        }
    });

    if(checked == $('input[name=checkRequi]').length){
        alert('La política de privacidad ha sido aceptada');
        return true;
    }else{
        alert('Debe aceptar la política de privacidad');
        return false;
    }

}
    
answered by 08.06.2017 в 22:02
0

You must give a different name to each checkbox, since when you have it you will overwrite it. You can also put them in the same css class and pick them up by class, then go through the elements

    
answered by 08.06.2017 в 21:46