How to use 'while' on an 'isNaN()'?

Asked

Viewed 81 times

3

I am doing a "quiz" test and to work the user has to type only numbers, if you do not type, an error message will be sent for him to repeat the process.

I was able to solve it with the following:

if (isNaN(variavel1)) 
{
    Variavel1 = Prompt("Só são permitido numeros, tente novamente ");
}

But the problem is, it only works once. If the user in the second attempt continues writing letters, the program does not command him to type again.

I tried to use the while but I’m not sure how to use for this particular case.
If you can help me, I’d appreciate it.

  • 1

    Why not validate with HTML5? Just put input type number and you’re done....

  • 2

    Yes, but I forgot to tell you, I’m learning Javascript. That’s why

1 answer

6


It is possible to validate in the event keyup... but I don’t recommend showing a popup, but something more subtle like changing the color of the text. See the example:

var tb = document.getElementById("num");
tb.addEventListener("keyup", function(e){
  tb.className = isNaN(tb.value) ? "invalid" : "valid";
});
.invalid {
  color: red;
  }
<input id="num" type="textbox" />

Browser other questions tagged

You are not signed in. Login or sign up in order to post.