I needed a great, unobtrusive way to notify a web site visitor that they can only enter whole numbers into fields on a web form. This is the JavaScript I came up with using jQuery and qTip This is easily modified to support numeric characters of any sort – decimal points, commas, whatever you want. It does not enforce any particular rules – it is primarily a keystroke filter.
I allow numbers and navigation keys, but disallow everything else. The code is documented inline.
Please don’t forget that if you use this to not rely on it for anything except relieving user frustration. You should always do server side validation as well
And this is the way it looks in my project:
.
One thing I should note: I’m using this together with Knockout.js without any weird side effects – they are working nicely together.
$(function()
{
$('input.intOnly' ).live( 'paste',
function(event)
{
// we could loop across the value and validate it, but I'm too lazy
event.preventDefault();
});
$("input.intOnly").live( 'blur',
function( event )
{
$(this).qtip('destroy');
});
$("input.intOnly").live( 'keydown',
function( event )
{
if (
event.keyCode == 46 || // delete
event.keyCode == 8 || // backspace
event.keyCode == 9 || // tab
event.keyCode == 224 || // command key on mac
event.keyCode == 18 || // alt key
event.keyCode == 16 || // shift key
event.keyCode == 17 || // control key
( event.keyCode >= 48 && event.keyCode <= 57 ) || // numbers
( event.keyCode >= 96 && event.keyCode <= 105 ) || // numeric keypad
( event.keyCode >= 37 && event.keyCode <= 40 ) // arrow keys
)
{
return;
}
event.stopImmediatePropagation();
event.preventDefault();
$(this).qtip(
{
content: 'Only whole numbers are allowed.',
show: { ready: true },
hide: { fixed: true, delay: 100000 }
});
});
});
Like this:
Like Loading...