简体   繁体   中英

Switch in function doesn't work

I wrote this just to learn the switch method, but for some reason it doesn't work as I intended, my function doesn't do anything. All I wanted to do is write a number in the value, the value then is checked in the switch method, and in case it's greater than zero, display a message, less than zero another message and so on.

Here is the whole thing

<!DOCTYPE html>
<html>
  <body>
    <p>Check if your number in relation to 0</p>

    <input id="in"></input>
  <br>
  <button onclick="check()">Check</button>

  <p id="display"></p>

  <script>

    function check() {

      var text;
      var val = document.getElementById("in").value;

      switch (true) {
        case (val < 0);
          text = "Numarul este mai mic decat zero";
          break;
        case (val > 0);
          text = "Numarul este mai mare decat zero";
          break;
        default:
          text = "Numarul este egal cu zero";
          break;
      }

      document.getElementById("display").innerHTML = text;
    }
  </script>

  </body>
</html>

The text in that language is just saying the number is less greater or equal to zero, doesn't matter, I forgot to translate it in English.

Please change ; after the case to :

case val > 0:
//          ^

(You do not need parenthesis between case and : )

case (val > 0); should be case (val > 0): . You end a case statement with a colon, not semi-colon.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM