How to get input using HTML and Javascript

Asked

Viewed 146,605 times

10

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

2 answers

18


In this simple example, it is possible to solve by treating only the event submit 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();
});

http://jsfiddle.net/vkxzf/

  • Won the right answer prize for Michael’s 403 :)

8

In the Javascript 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".

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

Example in jsFiddle

  • Michael, your example is giving Forbbiden 403. I think Alert() is alerted as some kind of XSS in Jsfiddle

  • Is that failed to prevent the sending of the form.

  • Oh yes, blunder. It’s sleep! = ) Anyway, I’m testing here and adding the e.preventDefault(); strange things happen (the field is reset, or the Alert does not appear). It is only possible to use the preventDefault with addEventListener? Example: http://jsfiddle.net/MUs87/4/

  • The preventDefault() that you use in the keydown worked normally for me. The other I think doesn’t work because you need to prevent the event submit form, not the button.

  • Oh yes, that’s right, thank you! Also, the keydown with preventDefault was making two Alerts appear in sequence for me. I switched to keypress and was cool. I will update the answer (although your solution is obviously better)

Browser other questions tagged

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