Home » How To » Cara Membuat Checkbox is Checked

Cara Membuat Checkbox is Checked

by Hanifah Nurbaeti
by Hanifah Nurbaeti

Kita akan mempelajari cara mengecek checkbox yang sudah dicentang dengan JavaScript.

<!DOCTYPE html>
<html>
<body>

<p>Tampilkan beberapa teks saat kotak centang dicentang:</p>

<label for="myCheck">Checkbox:</label> 
<input type="checkbox" id="myCheck" onclick="myFunction()">

<p id="text" style="display:none">Checkbox is CHECKED!</p>

<script>
function myFunction() {
  var checkBox = document.getElementById("myCheck");
  var text = document.getElementById("text");
  if (checkBox.checked == true){
    text.style.display = "block";
  } else {
     text.style.display = "none";
  }
}
</script>

</body>
</html>

Checkbox is Checked

Langkah 1) Tambahkan HTML:
Contoh

Checkbox: <input type="checkbox" id="myCheck" onclick="myFunction()">

<p id="text" style="display:none">Checkbox is CHECKED!</p>

Langkah 2) Tambahkan JavaScript:
Contoh

  // Dapatkan checkbox
  var checkBox = document.getElementById("myCheck");
  //d Dapatkan output teks
  var text = document.getElementById("text");

  // Jika checkbox telah dicentang, tampilkan teks keluaran
  if (checkBox.checked == true){
    text.style.display = "block";
  } else {
    text.style.display = "none";
  }
}

You may also like