I've got a code like this to enable or disable som text inputs when a checkbox is marked.
$(document).ready(function(){
$(":checkbox").change(function(){
if(this.checked){
$("input:text").attr('disabled', true);
} else {
$("input:text").attr('disabled', false);
}
});
});
It seems to work when the user clicks on the checkbox, but the javascript can change the checkbox value by invoking:
$(":checkbox").attr('checked', true);
When the checkbox is changed by the javascript the event is not fired. I've tried with click() event but happens the same.
Any idea?
Thanks.
First, let's slim down that event handlers, since you're passing a boolean to .attr('disabled', bool)
and .checked
is a boolean, let's take advantage of it, like this:
$(function(){
$(":checkbox").change(function(){
$("input:text").attr('disabled', this.checked);
});
});
Then when changing the value programmatically just trigger the change
event as well, like this:
$(":checkbox").attr('checked', true).change();
.change()
without parameters is a shortcut for .trigger("change")
, which will cause your event handler to run.
manually invoke the change event:
$(":checkbox").change();
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