Apr 122013
 

Raramente accade di dover controllare gli input da tastiera, con JQuery possiamo fare un binding degli eventi del tutto simile a quello per gli eventi del mouse.

Nella nostra pagina html predisponiamo un campo di input dove scrivere e tre paragrafi dove riportare la gestione degli eventi:


<input type="text">
<h1>Keydown</h1>
<p id="keydown"></p>
<h1>Keyup</h1>
<p id="keyup"></p>
<h1>Keypress</h1>
<p id="keypress"></p>

Poi come sempre al document.ready andiamo a mappare 3 eventi particolari: keydown, keyup e keypress. Passiamo l’event alla funzione in modo da sapere, e scrivere nella porzione html opportuna, il target dove si è scatenato l’evento, il tipo di evento. L’ultimo valore, which, sarà in vece il charCode, che puoi approfondire qui.


$(document).ready(function() {
$('input').keydown(function(event) {
$('#keydown').html('target = ' + event.target + '<br>' +
'type = ' + event.type + '<br>' +
'which = ' + event.which + '<br>');
});
$('input').keyup(function(event) {
$('#keyup').html('target = ' + event.target + '<br>' +
'type = ' + event.type + '<br>' +
'which = ' + event.which + '<br>');
});
$('input').keypress(function(event) {
$('#keypress').html('target = ' + event.target + '<br>' +
'type = ' + event.type + '<br>' +
'which = ' + event.which + '<br>');
});
});

L’esempio

Sorry, the comment form is closed at this time.