How to make Javascript read a value given by a user?

Asked

Viewed 3,490 times

-2

How do I make Javascript read what the user types? As if it were leia() portugol.

2 answers

3


Use the method prompt() to collect data in a pop-up, and alert() to show something in a pop-up:

var texto = prompt('insira texto aqui');
alert(texto);

1

In the code below (I didn’t use jQuery) there are two events: one to detect the key at the time the value is entered in the input, and another to detect the click on "Send".

// Função que mostra o valor do input num alert
function mostrarValor() {
    alert(document.getElementById("meu-input").value);
}

// Evento que é executado toda vez que uma tecla for pressionada no input
document.getElementById("meu-input").onkeypress = function(e) {
    // 13 é a tecla <ENTER>. Se ela for pressionada, mostrar o valor
    if (e.keyCode == 13) {
        mostrarValor();
        e.preventDefault();
    }
}

// Evento que é executado ao clicar no botão de enviar
document.getElementById("meu-submit").onclick = function(e) {
    mostrarValor();
    e.preventDefault();
}
<form method="get">
    <input type="text" id="meu-input" />
    <input type="submit" id="meu-submit" value="Enviar" />
</form>

Browser other questions tagged

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