jQuery checkbox check/uncheck

This question already has an answer here:

  • Setting “checked” for a checkbox with jQuery? 38 answers

  • Use .prop() instead and if we go with your code then compare like this:

    Look at the example jsbin :

      $("#news_list tr").click(function () {
        var ele = $(this).find(':checkbox');
        if ($(':checked').length) {
          ele.prop('checked', false);
          $(this).removeClass('admin_checked');
        } else {
          ele.prop('checked', true);
          $(this).addClass('admin_checked');
        }
     });
    

    Changes:

  • Changed input to :checkbox .
  • Comparing the length of the checked checkboxes .

  • Use prop() instead of attr() to set the value of checked . Also use :checkbox in find method instead of input and be specific.

    Live Demo

    $("#news_list tr").click(function() {
        var ele = $(this).find('input');
        if(ele.is(':checked')){
            ele.prop('checked', false);
            $(this).removeClass('admin_checked');
        }else{
            ele.prop('checked', true);
            $(this).addClass('admin_checked');
        }
    });
    

    Use prop instead of attr for properties like checked

    As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method


     $('mainCheckBox').click(function(){
        if($(this).prop('checked')){
            $('Id or Class of checkbox').prop('checked', true);
        }else{
            $('Id or Class of checkbox').prop('checked', false);
        }
    });
    
    链接地址: http://www.djcxy.com/p/12252.html

    上一篇: 如何取消选中选中的单选按钮

    下一篇: jQuery复选框选中/取消选中