Is it right to display the table of digit?

Viewed 67

I want to display the multiplication table of input digit but this code is not working well by using switch statement. Please tell me where is mistake in this code.

const tables = (num) => {
  switch (num.value) {
    case num.value.match(/[0-9]+$/):
      for (var i = 1; i <= 10; i++) {
        document.write(`${num.value} * ${i} = ${num.value * i}<br>`)
      }
      break;
    default:
      return alert(`Invalid Entry!`)
      break;
  }
}
<body>

  <p>Enter a number to get table: </p>
  <input id="number" type="text">
  <input type="submit" onclick="tables(number)">

</body>

1 Answers

This is a classic use case for an if statement:

const input = document.getElementById('number')
const button = document.getElementById('button')

button.addEventListener('click', tables)


function tables() {
  const value = input.value

  if (null === value.match(/^[0-9]+$/)) {
    // if the value doesn't only consist of numeric symbols
    // alert a message and return (stop executing the function)
    alert(`Invalid Entry!`)
    return 
  }

  // if the user input is valid, proceed with the output
  for (let i = 1; i <= 10; i++) {
    document.write(`${value} &times; ${i} = ${value * i}<br>`)
  }
}
<p>Enter a number to get table: </p>
<input id="number" type="text">
<input id="button" type="submit">

Read about the difference between if and switch here.

Please also note that the regular expression you provided will not always work as intended, since it asserts that any number of digits can be found at the end of the string, without accounting for anything that comes before that. I added the start position symbol (^) to make sure that only strings containing only numbers from start to finish pass the test.

Related