How to allow only numbers in a javascript prompt?

Asked

Viewed 1,080 times

4

I want me to be able to put only numbers when inserting something in the prompt.

var count = prompt("Teste");

How can I do it?

1 answer

4

You can create a version of prompt for this we insist until the user type 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 function isNaN is used to verify whether the user has entered a number or not.

Browser other questions tagged

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