Why isn't my checkbox change event triggered?

后端 未结 3 1797
栀梦
栀梦 2020-12-03 07:20

I have two functions.

The first function translates a div click into a checked/unchecked toggle. The second function translates a checkbox change into a hide/show ev

相关标签:
3条回答
  • 2020-12-03 07:59

    Don't bother with the first snippet. Just use LABEL elements:

    <label><input type="checkbox">Some option</label>
    

    Now, when the user clicks the label (the text next to the checkbox), the checkbox will be activated.


    The second snippet can be optimized:

    $('input:checkbox').change(function() {
        $('#' + this.id).toggle(this.checked);
    });
    
    0 讨论(0)
  • 2020-12-03 08:03

    The change event does not fire when you programmatically change the value of a check box. What you can do to ensure it fires is:

     $(":checkbox").parent().click(function(evt) {
        if (evt.target.type !== 'checkbox') {
            var $checkbox = $(":checkbox", this);
            $checkbox.attr('checked', !$checkbox.attr('checked'));
            $checkbox.change();
        }
    });
    
    0 讨论(0)
  • 2020-12-03 08:09

    you are using '.' which is for class selectors instead use '#' since you are using the element ID. Like this:

    $(document).ready(function() {
        $(":checkbox").bind('change', function() {
            if($(this).attr("checked")) {
                $('#'+this.id).show();
            }
            else {
                $('#'+this.id).hide();
            }
        });
    });
    
    0 讨论(0)
提交回复
热议问题