Ad

Why Is There No Increment To Change The Case In My Switch Statement?

- 1 answer

What I intend to achieve with this code is that on click of the "Click Me!" button it should increment num +1 so it would change then the case. Eg. from case 0 to case 1 in the switch statement. But all I get back is undefined. I tried to have the switch statement and the num++ function on their own but didn't work as well. Any help is appreciated towards the solution.

var btn=document.querySelector("button")
    var text="test"
    var num

function changeCase () {
  btn.addEventListener(onclick, function (){num++})
  switch (num) {
  case 0:
    text = "Off";
    break;
  case 1:
    text = "On";
    break;
  default:
    text = "No value found";
  }
}

    document.getElementById("demo").innerHTML = text;
<h1>Hello!</h1>
    <div>
      <button onclick="changeCase()">Click Me!</button>
      <p id="demo"></p>
    </div>

Ad

Answer

A couple of things:

  • You're not doing anything with text after changing it in changeCase. You've only used it once, on page load.

  • You're using both an onclick attribute and then also, when that's clicked, you're trying to add an event listener for click.

  • You're using onclick as an identifier in the addEventListener call, but you wanted "click" as a string (and no "on").

  • You probably want to set an initial value for num, instead of leting it default to the value undefined. If you do num++ when num has undefined in it, you'll get NaN, which doesn't match any of your cases.

To fix it:

  • Don't use onclick attributes, use addEventListener.

  • Use text after changing it.

  • Add the value for num.

Here's an example:

var btn=document.querySelector("button");
var text="test";
var num = 0;

btn.addEventListener("click", function (){
    num++;
    changeCase();
});

function changeCase () {
    switch (num) {
        case 0:
            text = "Off";
            break;
        case 1:
            text = "On";
            break;
        default:
            text = "No value found";
            break;
    }
    document.getElementById("demo").innerHTML = text;
}

changeCase();
<h1>Hello!</h1>
    <div>
      <button>Click Me!</button>
      <p id="demo"></p>
    </div>

Ad
source: stackoverflow.com
Ad