6

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.

4
  • Have you tried using $('#idCheckbox').trigger('change'); (or click event)? Maybe it's not firing event, only changing state? Commented Jan 16, 2014 at 14:48
  • 3
    Programmatic changes (i.e. changes made by code rather than user interaction) don't trigger change events, unfortunately. Commented Jan 16, 2014 at 14:59
  • The change event isn't fired when an attribute of an element is modified. Commented Jan 16, 2014 at 14:59
  • So it is not possible? Commented Jan 16, 2014 at 15:02

3 Answers 3

9

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/

Sign up to request clarification or add additional context in comments.

1 Comment

I can't do $("#idCheckbox").click(); Is another script different than mine which check the check-box. Thanks anyway
1

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");


});

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.