Home > Software engineering >  If we select all checkbox manually how to get selected selectAll checkbox in jquery?
If we select all checkbox manually how to get selected selectAll checkbox in jquery?

Time:11-21

how to do it? i can do this

<input type='checkbox' id='selectAll'/>
<input type='checkbox' id='select1' class='select'/>
<input type='checkbox' id='select2' class='select'/>

jquery to select all when #selectAll checked

    $('#selectAll').click(function(){
    if($(this).prop("checked")) {
        $(".select").prop("checked", true);
    } else {
        $(".select").prop("checked", false);
    }                
});

how to do it in reverse? if I checked #select1 and #select2 then #selectAll get checked automatic.....

CodePudding user response:

This piece of shorter code could work as expected.

$('#selectAll').click(function() {
  $(':checkbox.select').prop('checked', $(this).is(':checked'));
});
$(':checkbox.select').click(function() {
  $('#selectAll').prop('checked', $(':checkbox.select').length === $(':checked.select').length);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='checkbox' id='selectAll'/>
<input type='checkbox' id='select1' class='select'/>
<input type='checkbox' id='select2' class='select'/>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Please try something like this

$('checkbox').click(function(){
    if($("#select1").prop("checked") && $("#select2").prop("checked")) {
        $("#selectAll").prop("checked", true);
    } else {
        $("#selectAll").prop("checked", false);
    }                
});




   $('checkbox').click(function(){
let n = number_of_checkboxes; // can be any number
let checked = 0;
for(let i = 1; i <= n; i  ){
if($("#select"   "'i'").prop("checked"){
checked = checked   1; // use parseInt if required
}
}

if(checked == n){
$("#selectAll").prop("checked", true);
}
else {
 $("#selectAll").prop("checked", false);
}
        });
  • Related