Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Keyboard events are a bit tricky as suggested on the jQuery docs.<br> <a href="http://unixpapa.com/js/key.html" rel="nofollow noreferrer">http://unixpapa.com/js/key.html</a><br> <a href="http://yehudakatz.com/2007/07/03/event-normalization-in-jquery-113/" rel="nofollow noreferrer">http://yehudakatz.com/2007/07/03/event-normalization-in-jquery-113/</a></p> <p>The difficulty that concerns you is this:<blockquote><b>Identifying Keys</b><br> When you catch a keyboard event, you may wish to know which key was pressed. If so, you may be asking too much. This is a very big mess of browser incompatibilities and bugs.<br> <i>From the first link above</i></blockquote></p> <p>All the same, in jQuery I'd do this:</p> <pre><code>textBoxElement.keydown( function( e ) { var chr = String.fromCharCode( e.which ); if( !/[0-9.]/.test( chr ) ) { e.preventDefault(); } } </code></pre> <p>This will also disable other important keys like enter, tab, delete, so they need to be added into the conditional. Not all the other keys are printable and so can't be regexed, so you'll have to check for their e.keyCode. 13, 8 etc.</p> <p>If you're not too bothered about the regex you could do something like</p> <pre><code>textBoxElement.keydown( function( e ) { switch( e.keyCode ) { case 48: //0 case 49: //1 case 50: //2 case 51: //3 case 52: //4 case 53: //5 case 54: //6 case 55: //7 case 56: //8 case 57: //9 case 48: //10 case 37: //left case 39: //right case 8: //tab case 13: //return case 46: //del case 190: //. return; } e.preventDefault(); }); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload