Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript switch statement fails to match case

Tags:

javascript

I have the following problem to solve.

Problem 5. Digit as word

Write a script that asks for a digit (0-9), and depending on the input, shows the digit as a word (in English). Print “not a digit” in case of invalid input. Use a switch statement. Examples:

digit   result
2       two
1       one
0       zero
5       five
-0.1    not a digit
hi      not a digit
9       nine
10      not a digit

=

Here's my JavaScript and HTML HTML:

<input type="text" id="textInput">
<button id="react">Check</button>
<p id="result"></p>

My JavaScript:

document.addEventListener("DOMContentLoaded",function(){

   var input = document.getElementById('textInput');
   var button = document.getElementById('react');
   var result = document.getElementById('result');


   button.addEventListener('click',function(){

       switch (input.value) {
           case 0:
               result.innerHTML = 'zero';
               break;
           case 1:
               result.innerHTML = 'one';
               break;
           case 2:
               result.innerHTML = 'two';
               break;
           case 3:
               result.innerHTML = 'three';
               break;
           case 4:
               result.innerHTML = 'four';
               break;
           case 5:
               result.innerHTML = 'five';
               break;
           case 6:
               result.innerHTML = 'Six';
               break;
           case 7:
               result.innerHTML = 'Seven';
               break;
           case 8:
               result.innerHTML = 'Eight';
               break;
           case 9:
               result.innerHTML = 'Nine';
               break;
           default:
               result.innerHTML = 'not a digit';
               break;
       }

   });

});

The problem is that when I type a number from 0-9 it shows the default statement.

like image 536
Nasco.Chachev Avatar asked Jul 06 '26 13:07

Nasco.Chachev


1 Answers

The value is in string format. Convert it to number because switch statements do not coerce types (unlike if statements)

switch(+input.value) {

OR

switch(parseInt(input.value, 10)) {

I'll also suggest to use array or object.

var arr = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];

result.innerHTML = arr[+input.value] || 'Not a Digit';
like image 173
Tushar Avatar answered Jul 08 '26 01:07

Tushar



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!