Mikel
Mikel

Reputation: 6222

Trigger a programmatically 'checked' checkbox with jQuery

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.

Upvotes: 6

Views: 19571

Answers (3)

achinmay
achinmay

Reputation: 31

When a checkbox is checked programmatically using javascript, onchange event does not get fired automatically. So the script that marks the checkbox as checked should call onchange event.

Upvotes: 1

RononDex
RononDex

Reputation: 4173

You can move your inline defined function to global scope and call it:

function checkBoxClick(){
    if($(this).is(':checked')){
        alert("Is checked!");
    }
}

$(function(){
    //create a trigger that if a checkbox changes, eg is clicked/change show an alert
    $("#idCheckbox").on("change", checkBoxClick);

    // Trigger your click function
    checkBoxClick();    

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


});

Upvotes: 1

hunter
hunter

Reputation: 63512

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/

Upvotes: 9

Related Questions