Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which jquery event to use?

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.

like image 738
Javi Avatar asked Feb 26 '23 18:02

Javi


2 Answers

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.

like image 189
Nick Craver Avatar answered Mar 05 '23 03:03

Nick Craver


manually invoke the change event:

$(":checkbox").change();
like image 34
Ali Tarhini Avatar answered Mar 05 '23 01:03

Ali Tarhini