2011-03-11 9 views

risposta

28

Si dovrà allegare un evento "keyup" per la casella di testo e dentro il controllo evento per il keycodes si desidera:

$("#hi").bind("keyup", function(e) { 
     //on letter number 
     if (e.which <= 90 && e.which >= 48) 
     { 
      alert('hello'); 
     } 
}); 
+1

non funziona quando si utilizza i numeri dalla tastiera. http://www.javascripter.net/faq/keycodes.htm – dreagan

1
<input id="textbox" type='text' id='hi /> 

$("#textbox").keypress(function (e){ 
    if (e.which <= 90 && e.which >= 48) 
     { 
      alert('Letter or number click'); 
     } 
}); 
11

Se si desidera controllare quale personaggio è stato digitato, keyup è l'evento sbagliato Solo l'evento keypress può dirti in modo affidabile qualcosa sul carattere digitato. Si può fare come segue: i conti

$("#hi").keypress(function(e) { 
    var charTyped = String.fromCharCode(e.which); 
    if (/[a-z\d]/i.test(charTyped)) { 
     alert("Letter or number typed: " + charTyped); 
    } 
}); 
+0

Perché l'evento keypress è più affidabile? – Kumar

+1

@ Kumar: Poiché 'keyup' e' keydown' sono interessati a quale tasto fisico è stato premuto mentre 'keypress' è interessato a quale input testuale è risultato dalla pressione del tasto. –

0
<input type="text" id="hi" onkeypress="keyPress()" /> 

function keyPress(e){ 
    var key, x = e || window.event; key = (x.keyCode || x.which); 
    if(key <= 90 && key >= 48){ 
    alert("Key pressed"); 
    } 
} 
0

Questo codice aggiunto per numeri, caratteri e cifre dal tastierino numerico:

document.querySelector(selector).addEventListener('keypress', function() { 
    if (e.which <= 90 && e.which >= 48 || e.which >= 96 && e.which <= 105) { 
    alert('keycode ' + e.which + ' triggered this event'); 
    //do whatever 
    } 
}); 
Problemi correlati