Question


I want to trigger an event not manually but by jQuery itself.
Here understand my problem better:

$('.commonCheck').change(function () {
            if ($(".cashierCheck").attr("checked")) {
                $('.cashierInput').fadeIn();
                console.log("________________hr")
            }
            else{
                $('.cashierInput').fadeOut();
                console.log("_______________uncjecked")
            }
}

My checkbox:

<input type="checkbox" name="cashierFilter" id="cashierFilter" class="cashierCheck commonCheck" class="mrL0" />

When i manually check/uncheck the checkbox the change event is triggered without any problem. But i want the event to be happened when i somehow execute this:

$('#cashierFilter').prop('checked','true');
Was it helpful?

Solution

Demo http://jsfiddle.net/ga9nn/

You can use trigger to fire events programatically:

$('#cashierFilter').prop('checked', true).trigger('change');

Also, you should use is to check the attributes of an element, and you can cache selectors in a variable to improve performance:

$('.commonCheck').change(function () {
    var $cashierCheck = $(".cashierCheck");
    if ($cashierCheck.is(":checked")) {
        $cashierCheck.fadeIn();
        console.log("________________hr")
    }
    else {
        $cashierCheck.fadeOut();
        console.log("_______________uncjecked")
    }
}

OTHER TIPS

Use "is" in jquery the best solution:

$('.commonCheck').change(function () {
    if ($(".cashierCheck").is(":checked")) {
                $('.cashierInput').fadeIn();
                console.log("________________hr")
            }
            else{
                $('.cashierInput').fadeOut();
                console.log("_______________uncjecked")
            }
});

http://jsfiddle.net/PpcLe/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top