N A
N A

Reputation: 841

jQuery click() on checkbox is not checking checkbox before running click handler

I was calling jQuery.click() on all my checkboxes when a global checkbox is checked. I want to disable a button if none of the normal checkboxes are checked. Hence, I was counting number of checked checkboxes using the code below. But when we manually click on .chkLst happens $(this) comes already checked and when I call click() function, $(this) comes unchecked.

$(".grid").on("click", ".chkLst", function() {
   if($(this).is(":checked")){
       deleteBtnDisableCheck++;
   } else {
       deleteBtnDisableCheck--;
   }
   if (deleteBtnDisableCheck == 0) {
        $('#btnDeleteLst').addClass("btnDisable");
   } else {
        $('#btnDeleteLst').removeClass("btnDisable");
   }
});

$(".grid").on("click", ".chkLstAll", function() {
    $(".chkLst").each(function() {
        $(this).click();
    });
});

Upvotes: 1

Views: 83

Answers (1)

Gopinath Shiva
Gopinath Shiva

Reputation: 3892

You can do the above operation easily using selector, so you dont require a counter variable. 

//function to call when local checkbox is clicked

$(".grid").on("click", ".chkLst", function() {
   callUpdateClassFunction();   
});

//function to call when global checkbox is clicked

$(".grid").on("click", ".chkLstAll", function() {
    $(".chkLst").prop('checked',this.checked);
    callUpdateClassFunction();  
});

//function to update class

function callUpdateClassFunction(){
 if($(".chkLst:checked").length > 0){
   $('#btnDeleteLst').addClass("btnDisable");
 }
 else{
   $('#btnDeleteLst').removeClass("btnDisable");
   }
}

Upvotes: 2

Related Questions