jqueryicheck

iCheck undo check


I want to do some validation when checkbox is checked and uncheck it if validation fails.

Right now, the checked property is false but the checkbox remains checked.

Mycode:

$("#Lve_InclWE").on('ifChecked', function(event){
    some_function();
    if(!some_validation())
        $('#Lve_InclWE').iCheck('uncheck');
});

HTML:

<div class="icheckbox_flat-green checked" style="position: relative;">
<input type="checkbox" class="icheck" id="Lve_InclWE" name="Lve_InclWE" style="position: absolute; opacity: 0;">

update1: Even if I do this, the problem remains:

$("#Lve_InclWE").removeProp("checked"); 
//$("#Lve_InclWE").prop("checked",false);
$("#Lve_InclWE").iCheck('update');

update2: Tried removing checked class at parent div but the same. Is it because I execute within the check event?

$('#Lve_InclWE').closest("div").removeClass("checked");

update3: I added an alert at the end of the "ifChecked" event and noticed that the checkbox actually been unchecked, but it returns to checked state after the event ends. Which means I cannot perform the undo check(uncheck) within the triggered event, any method you can think of?


Solution

  • The solution and possible the ONLY solution is to uncheck the checkbox AFTER event ended, using setTimeOut(fn,0)

    $("#Lve_InclWE").on('ifChecked', function(event){
        if(!validation()){
            setTimeout(function(){
                $('#Lve_InclWE').iCheck('uncheck');
            },0);
        }
    });
    

    The reason is because the checkbox always set to checked state after the triggered event.

    If you have another solution feel free to comment.