Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html button is not coming up with alert message from case function

I am trying to use case statements to give me three different alerts for three different button presses

I have tried

<!DOCTYPE html>
<html>
<head>
<script>
function something(){
 var counter = 0;
var button = document.querySelector("#button");

button.addEventListener("click", function() {
counter++;
switch(counter) {
    case 1:
        alert("something");
        break;
    case 2:
        alert("something else");
        break;
    case 3:
        alert("something else else");
        break;
  }
 });
 }

</script>
</head>
<body>
<input id="button" value="enter" type="button">
</body>
</html>

There are no errors in the console. The button is showing up on the webpage but not the alerts.

like image 968
Weston Avatar asked Dec 27 '25 15:12

Weston


1 Answers

As Jaromanda points out, you need to invoke the function as well as defining it, like:

function something() {
  var counter = 0;
  var button = document.querySelector("#button");

  button.addEventListener("click", function() {
    counter++;
    switch (counter) {
      case 1:
        alert("something");
        break;
      case 2:
        alert("something else");
        break;
      case 3:
        alert("something else else");
        break;
    }
  });
}
something();
<input id="button" value="enter" type="button">

Alternatively, it might be more intuitive to set up the code this way, identifying the button and the counter variable outside of the function, then incrementing the counter each time the function is called (inside the function.)

(Note: This version includes two additional features:

1) The if statement resets the counter to zero if it gets too high, so every click results in an alert. Just remove this statement (or comment it out) if you prefer for clicks beyond the third to do nothing.

2) There's a default case in the switch statement -- in case something went wrong and our code gave an unexpected value to the counter, this would help us debug that problem.)

const button = document.querySelector("#button");
let counter = 0;
button.addEventListener("click", doAlert);

function doAlert(){
  if (counter == 3){ counter = 0; }
  counter++;
  switch (counter) {
    case 1: alert("something"); break;
    case 2: alert("something else"); break;
    case 3: alert("something else else"); break;
    default: alert("this should be impossible"); break;
  }
}
<input id="button" value="Enter" type="button">
like image 87
Cat Avatar answered Dec 31 '25 18:12

Cat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!