2014-03-05 190 views
1

我有以下功能“选择所有复选框”和“取决于复选框”,但它不工作,因为我想要的。 1.如果我选择“全部选择”,“受控”复选框将保持禁用状态 2.当使用“控制器”启用“受控”复选框并且使用“全选”时,“受控”chaboxbox保持活动状态。当他们没有被选中时,我需要他们不活跃。选择所有,取决于复选框

我试图创建if语句(注释)来解决这个问题,但它不像预期的那样工作。是否有其他解决方案,或者在取消选择“全选”复选框后重置复选框可能会更好?在重置的情况下,我需要重置只有一组复选框,而不是整个表单。

$('form').ready(function() { 
    var $check1 = $('input[id*=selectAll]'), 
     $check2 = $('tr th :checkbox'), 
     $checkAll = $check1.add($check2); 
    $checkAll.on('click keydown', function() { 
     var checkedStatus = this.checked, 
      $selected1 = $(this).closest(".formFieldWrapper").find('input:checkbox:not(:first):not([data-leader])'), 
      $selected2 = $(this).closest("table").find('tr td :checkbox'), 
      $selectedAll = $selected1.add($selected2); 
      $selectedAll.each(function() { 

      // if($checkAll.prop('checked', true)) { 
      $(this).prop('checked', checkedStatus) //.prop('disabled', false) 
      // } else { 
      // $(this).prop('checked', checkedStatus); 
      // $checkAll.prop('checked', false); 
      // $('.controlled').prop('disabled', true) 
      // } 

     }); 
     $selectedAll.on('click keydown', function(){ 
     $checkAll.prop('checked', false) 
     }); 
    }); 
}); 

$('.controlled').prop('disabled', true); 
$('.controller').click(function() { 
    var $this = $(this), 
     $inputs = $($this.data('target')); 
    $inputs.prop('disabled', !this.checked); 
    if (!this.checked) { 
     $inputs.prop('checked', false); 
    } 
}); 

JSFiddle

回答

0

解决方案:

var $check1 = $('input[id*=selectAll]'), 
     $check2 = $('tr th :checkbox'), 
     $checkAll = $check1.add($check2); 

    $checkAll.on('click keydown', function() { 
     var checkedStatus = this.checked, 
      $selected1 = $(this).closest(".formFieldWrapper").find('input:checkbox:not(:first):not([data-leader])'), 
      $selected2 = $(this).closest("table").find('tr td :checkbox'), 
      $selectedAll = $selected1.add($selected2); 

     $selectedAll.each(function() { 
      $(this).prop('checked', checkedStatus); 

      if (checkedStatus === true) { 
       $('.controlled').prop('disabled', false); 
      } else { 
       $('.controlled').prop('disabled', true); 
      } 

     }); 

     $selectedAll.on('click keydown', function() { 
      $checkAll.prop('checked', false) 
     }); 
    }); 


$('.controlled').prop('disabled', true); 
$('.controller').click(function() { 
    var $this = $(this), 
     $inputs = $($this.data('target')); 

    $inputs.prop('disabled', !this.checked); 
    if (!this.checked) { 
     $inputs.prop('checked', false); 
    } 
});