jQuery核取方塊checkbox的全選和反選

antzone發表於2018-06-04

分享一個常見操作,核取方塊全選和反選效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script src="mytest/jQuery/jquery-1.8.3.js"></script>
<script> 
$(document).ready(function() { 
  $("#checkAllChange").click(function(){ 
    if(this.checked == true) { 
      $(".userid").each(function(){ 
        this.checked = true; 
      }); 
    } 
    else { 
      $(".userid").each(function(){ 
        this.checked = false; 
      }); 
    } 
  }); 
  //全選 
  $("#checkAll").click(function(){ 
    $(".userid").each(function(){ 
      this.checked = true; 
    }); 
  }); 
  //取消全部 
  $("#removeAll").click(function(){ 
    $(".userid").each(function(){ 
      this.checked = false; 
    }); 
  }); 
  // 反選 
  $("#reverse").click(function(){ 
    $(".userid").each(function() { 
      if (this.checked == true) { 
        this.checked = false; 
      } 
      else{ 
        this.checked = true; 
      } 
    }) 
  }); 
  //批量刪除 
  $("#delAll").click(function(){ 
    var arrUserid = new Array(); 
    $(".userid").each(function(i){ 
      if(this.checked == true) { 
        arrUserid[i] = $(this).val(); 
      } 
    }); 
    alert("批量刪除的:" + arrUserid); 
  }); 
}); 
</script>
</head>
<body>
<table border="1">
  <tr>
    <td><input type="checkbox" id="checkAllChange" /></td>
    <td>使用者id</td>
    <td>使用者名稱</td>
    <td>電話</td>
    <td>地址</td>
  </tr>
  <tr>
    <td><input type="checkbox" class="userid" value="1" /></td>
    <td>1</td>
    <td>wangzs1</td>
    <td>18888000</td>
    <td>浦東</td>
  </tr>
  <tr>
    <td><input type="checkbox" class="userid" value="2" /></td>
    <td>2</td>
    <td>wangzs2</td>
    <td>18888001</td>
    <td>上海</td>
  </tr>
  <tr>
    <td><input type="checkbox" class="userid" value="3" /></td>
    <td>3</td>
    <td>wangzs3</td>
    <td>18888002</td>
    <td>河南</td>
  </tr>
  <tr>
    <td><input type="checkbox" class="userid" value="4" /></td>
    <td>4</td>
    <td>wangzs4</td>
    <td>18888003</td>
    <td>許昌</td>
  </tr>
  <tr>
    <td></td>
    <td><input type="button" id="checkAll" value="全選" /></td>
    <td><input type="button" id="removeAll" value="取消全部" /></td>
    <td><input type="button" id="reverse" value="反選" /></td>
  </tr>
  <tr>
    <td colspan="4" align="center"><input type="button" value="批量刪除" id="delAll"></td>
  </tr>
</table>
</body>
</html>

相關文章