How to get input using HTML and JavaScript

6

As a beginner in the 'JS' language, I would like to know how to simply get text from a <form> (without forwarding to another page and without changing the URL) and passing to a function like alert() when the user enter no <input> (text / password) or click <input> (submit).

    
asked by anonymous 19.06.2014 / 03:01

2 answers

12

In this simple example, you can solve by treating only the submit event of the form itself:

<form id="formulario">
    <input type="text" id="campo">
    <input type="submit" value="Enviar">
</form>
var form = document.getElementById('formulario');
var campo = document.getElementById('campo');

form.addEventListener('submit', function(e) {
    // alerta o valor do campo
    alert(campo.value);

    // impede o envio do form
    e.preventDefault();
});

link

    
19.06.2014 / 03:38
5

In the Javascript code below (I did not use jQuery), there are two events: one to detect the key at the moment the value is entered in input , and another to detect the click on the "Submit" button.

HTML:

<form method="get">
    <input type="text" id="meu-input" />
    <input type="submit" id="meu-submit" value="Enviar" />
</form>

Javascript:

// 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();
}

jsFiddle Example

    
19.06.2014 / 03:11