简体   繁体   中英

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.

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.

手动调用change事件:

$(":checkbox").change();

很抱歉,如果我太简单了,但是当你更改复选框值时,你不能让JavaScript手动调用该事件吗?

You could try to fire the event manually:

$(":checkbox").attr('checked', true);
$(":checkbox").change();

or

$(":checkbox").attr('checked', true).change();

You can just .trigger() the change event manually:

$('input:checkbox').trigger('change');

You should never use a selector like :checkbox . It's an implicit usage of the universal * selector which will query all nodes on your site, which is pretty bad, which means it's pretty slow.

input:checkbox will still query all of your checkbox elements, you should us a class or an id to query for a specific element.

Ref.: .trigger()

I don't know why changing the checkbox through javascript doesn't fire the event. But, i have a solution for this.

make

function(){
        if(this.checked){
            $("input:text").attr('disabled', true);
        } else {
            $("input:text").attr('disabled', false);
        }
      }

as a function. Such as function cb_change_handler(){ ...} and u can manually use this function when changing the value by javascript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM