How to only allow numbers at a prompt in javascript?

4

I want to be able to put only numbers when I insert something into the prompt.

var count = prompt("Teste");

How can I do this?

    
asked by anonymous 09.07.2018 / 07:58

1 answer

4

You can create a version of prompt for this that insists until the user enters a number in the form you want:

function promptInt(mensagem, tenteNovamente) {
    var msg = mensagem;
    while (true) {
        var ret = parseInt(prompt(msg));
        if (!isNaN(ret)) return ret;
        msg = tenteNovamente;
    }
}

var count = promptInt("Teste", "Por favor, digite um número.\nTente novamente.");
alert("Você digitou o número " + count + ".");

The isNaN function is used to check whether the user entered a number or not.

    
09.07.2018 / 08:33