JQuery - Checkbox on-change event doesn't fire if checked using JQuery

后端 未结 5 889
忘掉有多难
忘掉有多难 2021-01-01 09:56

I have this Check All function which check all check boxes. I use JQuery to do that.

But I also have this on change function that toggle a

相关标签:
5条回答
  • 2021-01-01 10:36

    Almost identical to visnu's answer, but directly calling click() will fire all the click events bound by jQuery. If you demo this, you will see it also unchecks the boxes, whereas his answer simply removes the highlight while they remain clicked.

    $(document).ready(function(){
        $("input[type='checkbox']").on('change', function(){
            $(this).closest('div').toggleClass('highlight');
        });
    
        $("#check_all").on('click', function(){
            $("input[type='checkbox']").click();
        });
    });
    
    0 讨论(0)
  • 2021-01-01 10:39

    You can try this,

    $(document).on('change','input[type="checkbox]' ,function(){
         // $this will contain a reference to the checkbox
          var $this = $(this);   
        if ($this.is(':checked')){//To CHECK CHECK BOX IS CHECKED OR NOT
             $(this).closest('div').toggleClass('highlight');
        }
    });
    

    Hope It Helps,

    0 讨论(0)
  • 2021-01-01 10:55

    After click check all you should call change() event like this

    $(document).ready(function(){
        $("input[type='checkbox']").on('change', function(){
            $(this).closest('div').toggleClass('highlight');
        });
    
        $("#check_all").on('click', function(){
            $("input[type='checkbox']").prop('checked', true).change();
        });
    });
    
    0 讨论(0)
  • 2021-01-01 10:57

    Check this fiddle modification of your code: http://jsfiddle.net/d4VTh/51/

    $(document).ready(function(){
        $("input[type='checkbox']").on('change', function(){
            if (this.checked)
                $(this).closest('div').addClass('highlight');
            else 
                $(this).closest('div').removeClass('highlight');
        });
    
        $("#check_all").on('click', function(){
            var item = $("input[type='checkbox']")
            item.prop('checked', !item.prop('checked')).change();
        });
    });
    
    0 讨论(0)
  • 2021-01-01 10:58

    This will trigger the change event, but only after you bind it first.

    $('input[type="checkbox]').trigger('change');
    
    0 讨论(0)
提交回复
热议问题