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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With