Nasco.Chachev
Nasco.Chachev

Reputation: 676

JavaScript switch statement fails to match case

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.

Upvotes: 3

Views: 2328

Answers (1)

Tushar
Tushar

Reputation: 87203

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';

Upvotes: 8

Related Questions