0

so i wrote an html page just for testing but i cant get the script work and its just says the alert and checks the checkbox but i wanna that when i check the checkbox the alert will appear. here's the code (without style.css).

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<header>
<p class="head1">SOME HEADING</p>
</header>
<div class="div1">
<h1>AN HEADING</h1>
<form>
<ul>
<li><input class="in1" id="checkboxid" type="checkbox">First Box</li>
<li><input class="in1" type="checkbox">Second Box</li>
<li><input class="in1" type="checkbox">Third Box</li>
</ul>
</form>
</div>
<script>
if (document.getElementById("checkboxid").checked = true) {
alert("You checked the first box.");
}
else {
alert("you didnt checked the box.");
}
</script>
</body>
</html>

1 Answers1

1

There is a mistake, you are using = instead of ===. Also, you can consider using a function change() that will be fired up when you first checkbox is checked or not.

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<header>
<p class="head1">SOME HEADING</p>
</header>
<div class="div1">
<h1>AN HEADING</h1>
<form>
<ul>
<li><input class="in1" id="checkboxid" type="checkbox" onclick="change()">First Box</li>
<li><input class="in1" type="checkbox">Second Box</li>
<li><input class="in1" type="checkbox">Third Box</li>
</ul>
</form>
</div>
<script>
function change(){
  if (document.getElementById("checkboxid").checked === true) {
    alert("You checked the first box.");
  }
  else {
    alert("you didnt checked the box.");
  }
}
</script>
</body>
</html>
edkeveked
  • 17,989
  • 10
  • 55
  • 93
  • oh ok thx, i fixed it now and used a function so it'll work only when i check the box and not on page load, thx to Swakeert Jain telling my question is a duplicate from another question (see comment on the question). so here's what i got now: `function checkbox() { if (document.getElementById("checkboxid").checked === true) { alert("You checked the first box."); } else { alert("you didnt checked the box."); } }` – Israel Shevkolenko Nov 20 '17 at 22:06
  • @IsraelShevkolenko, Great, you solved it! Happy coding! You can mark the answer as accepted and upvote it. – edkeveked Nov 20 '17 at 22:09