I've been trying to use for loop via user input but for some reason it neither shows the error nor shows the output

Viewed 41

I've been trying to use for loop via user input but for some reason it neither shows the error nor shows the output. here is my code below:-

<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>js recap</title>
</head>

<body>
  <form class="addform">
    <input type="number" name="text" id="text">
  </form>

<!-- START JAVASCRIPT -->

  <script>
    const addform = document.querySelector('.addform');

    addform.addEventListener('submit', e => {
      const todos = addform.text.value.trim();
      e.preventDefault();
      if (todos === typeof Number) {
        for (let i = 0; i <= todos; i++) {
          console.log(i);
        }
      }
    });
  </script>

<!-- END JAVASCRIPT-->
</body>

</html>

3 Answers

some notes:

  • e.target.value.trim() returns a string

  • use typeof todos === "number" or you can use !isNaN(todos) to check if a variable is a type of number ( isNaN means is not a number add the negation to it !isNaN to check if its a number )

  • parseInt() to convert the string retrieved from e.target.value.trim() to a number

<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>js recap</title>
</head>

<body>
  <form class="addform">
    <input type="number" name="text" id="text">
  </form>

<!-- START JAVASCRIPT -->

  <script>
    const addform = document.querySelector('.addform');

    addform.addEventListener('submit', e => {
      e.preventDefault();
      
      const todos = parseInt(addform.text.value.trim())

      if (typeof todos === "number") {
        for (let i = 0; i <= todos; i++) {
          console.log(i);
        }
      }
    });
  </script>

<!-- END JAVASCRIPT-->
</body>

</html>

Add a button to submit your form (click event in this example). You can use parseInt to convert string to a number data type.

var addform = document.querySelector('#text');
var boton = document.querySelector("#boton");

boton.addEventListener('click', e => {
  var todos = parseInt(addform.value.trim());
  e.preventDefault();

  if (typeof todos === 'number') {
    for (let i = 0; i <= todos; i++) {
      console.log(i);
    }
  }
});
<input type="number" name="text" id="text">
<button id="boton"> Go </button>

Any value that a user enters via the DOM comes through as text. You need to convert it into a number and then run the loop.

You can do:

if( !isNaN( Number(todos) ))

The if statement that you have is never true. So the code never executes.

You can check it by adding a console log just for the check.

console.log('%c Check the input value.', 'background:grey; padding:10px; color:#fff', typeof todos, todos);
Related