如何用 JavaScript 檢測複選框是否被選中?


要使用 JavaScript 檢查複選框是否被選中,程式碼如下 −

示例

 即時演示

<!DOCTYPE html>
<html>
<head>
<h1>Displaying textBox when a checkbox is checked</h1>
Checkbox: <input type="checkbox" class="check" onclick="checkFunction()" />
<h2 class="textBox" style="display:none">Checkbox is checked!!!</h2>
<script>
   document.querySelector(".check").addEventListener("click", checkFunction);
   function checkFunction() {
      var checkBox = document.querySelector(".check");
      var textBox = document.querySelector(".textBox");
      if (checkBox.checked == true) {
         textBox.style.display = "block";
      } else {
         textBox.style.display = "none";
      }
   }
</script>
</body>
</html>

輸出

這將產生以下輸出 −

點選複選框後 −

更新日期:06-5-2020

810 次瀏覽

開啟您的 職業生涯

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.