JavaScript checkbox全選和全不選效果

antzone發表於2017-04-13

分享一段極為簡單的程式碼例項,利用JavaScript實現checkbox核取方塊全選和全不選效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script type="text/javascript">
  function checkAll(ospan,cka) {
  var items = document.getElementsByTagName("input");
  if (ospan.innerHTML == "全選") {
    ospan.innerHTML = "取消"
  } else {
    ospan.innerHTML = "全選"
  }
  for (var index = 0; index < items.length; index++) {
    items[index].checked = cka.checked;
  }
}
window.onload = function () {
  var ospan = document.getElementsByTagName("span")[0];
  var cka = document.getElementById("all");
  cka.onclick = function () {
    checkAll(ospan,cka);
  }
}
</script>
</head>
<body>
  <input type="checkbox" id="all"><span>全選</span><br/>
  <input type="checkbox" name="item">數學<br/>
  <input type="checkbox" name="item">英語<br/>
  <input type="checkbox" name="item">物理<br/>
</body>
</html>

相關文章