2013-04-15 18 views
8

Ho un input e vorrei semplicemente aggiungere un listener di eventi per attivare una funzione quando premo Invio, quando l'input è focalizzato. Come faccio a farlo con puro JS?funzione execute su tasto invio

In questo momento ho:

HTML:

 Enter your wage:<input type="text" id="wage" value ="" size=20> 
     <button id="sub">Submit</button> 

Javascript:

var wage = document.getElementById("wage"); 
    wage.addEventListener("change", validate); 

    var btn = document.getElementById("sub"); 
    btn.addEventListener("click", validate); 

Quindi, in pratica la funzione validate() attiva quando si fa clic o si modifica il testo, ma voglio per chiamarlo premendo enter.

risposta

16

È possibile utilizzare questo:

var wage = document.getElementById("wage"); 
wage.addEventListener("keydown", function (e) { 
    if (e.keyCode === 13) { //checks whether the pressed key is "Enter" 
     validate(e); 
    } 
}); 

function validate(e) { 
    var text = e.target.value; 
    //validation of the input... 
} 

Live demo here

+0

+1. Sebbene tu possa sostituire 'alert()' con 'validate()'. – nnnnnn

+0

Sì, modificato :-) –

+1

Grazie. Funziona su tutti i browser? – frrlod

0

si avrebbe bisogno di qualcosa di simile a wage.addEventListener('keydown', validate);

La funzione validate sarebbe poi necessario verificare event.keyCode == 13 per determinare 'enter' pressione di un tasto.

0

Se si cambia il vostro elemento pulsante per un

<input type="submit" value="Submit"> 

che possa funzionare con il tasto Invio sulla tastiera.

4
var elem = document.getElementById("wage"); 
elem.onkeyup = function(e){ 
    if(e.keyCode == 13){ 
     validate(); 
    } 
} 

Esempio di lavorohttp://jsfiddle.net/aMgLK/

0

O con jQuery

$("#wage").on("keydown", function (e) { 
    if (e.keyCode === 13) { //checks whether the pressed key is "Enter" 
     validate(e); 
    } 
}); 
0
$(document).on('keyup', function(e){ 
    var key = e.which; 
    if(key == 13) // the enter key ascii code 
    { 
     login(); 
    } 
});