Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 218
Mikel Avatar asked Jan 16 '14 14:01

Mikel


1 Answers

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/

like image 174
hunter Avatar answered Oct 12 '22 03:10

hunter