2025-06-08

【jQuery】jQuery + CSS 多個 checkbox 勾選

  1.  
  2. <html>
  3. <head>
  4. <title>checkbox lab</title>
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  6. <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
  7. <script>
  8. // chkAll 點擊事件
  9. function checkAll() {
  10. var isChecked = $('#chkAll').prop('checked');
  11. // 更新所有 nameCheckbox 的狀態
  12. $('.nameCheckbox').prop('checked', isChecked).trigger('change');
  13. }
  14.  
  15.  
  16. // 更新 chkAll 狀態
  17. function updateChkAll() {
  18. var totalCheckboxes = $('.nameCheckbox').length;
  19. var checkedCheckboxes = $('.nameCheckbox:checked').length;
  20. var $chkAll = $('#chkAll');
  21. if (checkedCheckboxes === 0) {
  22. // 全部未選中
  23. $chkAll.prop('checked', false);
  24. $chkAll.removeClass('partial');
  25. } else if (checkedCheckboxes === totalCheckboxes) {
  26. // 全部選中
  27. $chkAll.prop('checked', true);
  28. $chkAll.removeClass('partial');
  29. } else {
  30. // 部分選中
  31. $chkAll.prop('checked', false);
  32. // 關鍵修改:部分選中時保持 checked 但變灰色
  33. $chkAll.prop('checked', true).addClass('partial');
  34. }
  35. }
  36. </script>
  37. <style type="text/css">
  38. #chkAll {
  39. margin-bottom: 10px;
  40. font-size: 10px;
  41. }
  42. /* 部分選中時的灰色打勾 */
  43. #chkAll.partial {
  44. accent-color: gray; /* 現代瀏覽器 */
  45. filter: grayscale(50%) opacity(80%); /* 舊瀏覽器備用 */
  46. }
  47. </style>
  48. </head>
  49. <body>
  50. <center>
  51. <form name="frmInput" id="frmInput" method="post" action="func.php">
  52. <input type="hidden" name="act" value="input" />
  53. <table border="1">
  54. <tr>
  55. <th nowrap="nowrap"><input type="checkbox" id="chkAll" onchange="checkAll()" />全選</th>
  56. <th nowrap="nowrap">姓名</th>
  57. </tr>
  58. <tr>
  59. <td><input type="checkbox" class="nameCheckbox" id="chk1" onchange="updateChkAll()" /></td>
  60. <td>張三</td>
  61. </tr>
  62. <tr>
  63. <td><input type="checkbox" class="nameCheckbox" id="chk2" onchange="updateChkAll()" /></td>
  64. <td>李四</td>
  65. </tr>
  66. <tr>
  67. <td><input type="checkbox" class="nameCheckbox" id="chk3" onchange="updateChkAll()" /></td>
  68. <td>王五</td>
  69. </tr>
  70. </table>
  71. </form>
  72. </center>
  73. </body>
  74. </html>
  75.  

沒有留言:

張貼留言