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

3

I am doing a test of "questionnaire" and to work the user has to enter only numbers, if not type, an error message will be issued for it to repeat the process.

I was able to resolve this with the following:

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

But the problem is that this only works once. If the user on the second attempt continues writing letters, the program does not have to type again.

I tried to use while but I'm not sure how to use it for this specific case. If you can help me, thank you.

    
asked by anonymous 11.09.2016 / 02:18

1 answer

6

It is possible to validate in the keyup event ... but I do not recommend showing a popup, but something 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" />
    
11.09.2016 / 04:25