Trigger a programmatically 'checked' checkbox with jQuery

Mikel picture Mikel · Jan 16, 2014 · Viewed 13.8k times · Source

I want to trigger a programmatically checked checkbox. eg:

$(function(){
    //create a trigger that if a checkbox changes, eg is clicked/change show an alert
    $("#idCheckbox").on("change", function(){
        if($(this).is(':checked')){
            alert("Is checked!");
        }
    });

    //onload put it checked
    $("#idCheckbox").attr("checked", "checked");
});

The 'problem' is that if I check on load the checkbox by javascript the on() method is not triggered, and the alert is not shown.

The code above is an example, in fact the script which check the checkbox is not mine and I can't modify it.

I am using jQuery 1.8.0

Any suggestion?

Thanks in advance.

Answer

hunter picture hunter · Jan 16, 2014

Rather than setting the attribute to checked you can call click() on the checkbox to trigger the the event you had bound previously


$(function(){
    var $checkbox = $("#idCheckbox");
    $checkbox.on("change", function(){
        if(this.checked){
            alert("Is checked!");
        }
    });

    $checkbox.click();
});

example: http://jsfiddle.net/hunter/wpLb2/