AlanTsai
1/2/2014 - 3:44 PM

選取所有checkbox和判斷是否全部checkbox已經被勾選

選取所有checkbox和判斷是否全部checkbox已經被勾選

<!DOCTYPE html>
<html>
<head>
<meta name="description" content="選取所有checkbox和判斷是否全部checkbox已經被勾選" />
<script src="http://code.jquery.com/jquery-latest.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  <form>
  <table>
    <tr>
      <th>
        <input type="checkbox" id="checkAll" />
      </th>
      <th>Name</th>
      <th>Age</th>
    </tr>
    <tr>
      <td>
        <input type="checkbox" name="chkPerson" />
      </td>
      <td>
        Jack
      </td>
      <td>
        18
      </td>
    </tr>
    <tr>
      <td>
        <input type="checkbox" name="chkPerson" />
      </td>
      <td>
        Alan
      </td>
      <td>
        26
      </td>
    </tr>
  </table>
  </form>
</body>
</html>
$(function(){

$('#checkAll').change(function() {
    //get all checkbox which want to change
    var checkboxes = $(this).closest('form').find('input[name="chkPerson"]:checkbox');
    if($(this).is(':checked')) {
        checkboxes.prop('checked', 'checked');
    } else {
        checkboxes.removeAttr('checked');
    }
});
  $('input[name="chkPerson"]').change(function(){
  checkOrRemoveCheckAll();
  });
});

function checkOrRemoveCheckAll(){
if($('input[name="chkPerson"]:checked').length == $('input[name="chkPerson"]').length)
    {
        $('#checkAll').prop("checked", "checked");
    }
    else
    {
        $('#checkAll').removeAttr("checked");
    }
}