使用jquery检查全部/取消全部选中

时间:2014-12-13 20:43:08

标签: jquery checkbox

我从cakephp生成的ctp文件中获得了这个标记。

这基本上是一个有兴趣爱好的复选框组。

所以,我想检查全部/取消选中所有使用jquery并且在检查完所有内容后如果取消选中一个框,检查所有将被删除,因此如果我选中所有单独的复选框,则会自动选中所有复选框。

我的代码:

<div class="checkgroup">
  <input type="checkbox" name="data[Student][hobby][]" value="checkAll" id="StudentHobbyCheckAll" />
  <label for="StudentHobbyCheckAll">Check All/Uncheck All</label>
</div>
<div class="checkgroup">
  <input type="checkbox" name="data[Student][hobby][]" value="sports" id="StudentHobbySports" />
  <label for="StudentHobbySports">Sports</label>
</div>
<div class="checkgroup">
  <input type="checkbox" name="data[Student][hobby][]" value="movies" id="StudentHobbyMovies" />
  <label for="StudentHobbyMovies">Movies</label>
</div>
<div class="checkgroup">
  <input type="checkbox" name="data[Student][hobby][]" value="netsurfing" id="StudentHobbyNetsurfing" />
  <label for="StudentHobbyNetsurfing">Netsurfing</label>
</div>
<div class="checkgroup">
  <input type="checkbox" name="data[Student][hobby][]" value="photography" id="StudentHobbyPhotography" />
  <label for="StudentHobbyPhotography">Photography</label>
</div>

2 个答案:

答案 0 :(得分:2)

http://jsfiddle.net/d5b01jdd/

var $chAll = $('#StudentHobbyCheckAll');
var $ch=$('.checkgroup input[type="checkbox"]').not($chAll);

$chAll.click(function () {
    $ch.prop('checked', $(this).prop('checked'));
});

$ch.click(function(){
    if($ch.size()==$('.checkgroup input[type="checkbox"]:checked').not($chAll).size())
        $chAll.prop('checked',true);
    else
        $chAll.prop('checked',false);
});

答案 1 :(得分:1)

这应该有效。 CODEPEN

$(function(){
  $('#StudentHobbyCheckAll').on('change', function() {
    $(this)
      .parents(':not(> :checkbox)')
      .find(':checkbox:gt(0)')
      .prop('checked', !$(this)[0].checked);
  }).change();
});
相关问题