Restricting Input in HTML Textboxes to Numeric Values
Ok, here’s a fairly basic one – how to force a textbox to accept only numeric input. Somebody asked me this today on a support call so I did a few quick lookups online and found the solutions listed rather unsatisfying. The main problem with most of the examples I could dig up was that they only include numeric values, but that provides a rather lame user experience. You need to still allow basic operational keys for a textbox – navigation keys, backspace and delete, tab/shift tab and the Enter key - to work or else the textbox will feel very different than a standard text box.
Yes, there are plug-ins that allow masked input easily enough but most are fixed width which is difficult to do with plain number input. So I took a few minutes to write a small reusable plug-in that handles this scenario. Imagine you have a couple of textboxes on a form like this:
<div class="containercontent">
<div class="label">Enter a number:</div>
<input type="text" name="txtNumber1" id="txtNumber1"
value="" class="numberinput" />
<div class="label">Enter a number:</div>
<input type="text" name="txtNumber2" id="txtNumber2"
value="" class="numberinput" />
</div>
and you want to restrict input to numbers. Here’s a small .forceNumeric() jQuery plug-in that does what I like to see in this case:
Updated thanks to Elijah Manor for a couple of small tweaks for additional keys to check for
<script type="text/javascript">
$(document).ready(function () {
$(".numberinput").forceNumeric();
});
// forceNumeric() plug-in implementation
jQuery.fn.forceNumeric = function () {
return this.each(function () {
$(this).keydown(function (e) {
var key = e.which || e.keyCode;
if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
// numbers
key >= 48 && key <= 57 ||
// Numeric keypad
key >= 96 && key <= 105 ||
// comma, period and minus, . on keypad
key == 190 || key == 188 || key == 109 || key == 110 ||
// Backspace and Tab and Enter
key == 8 || key == 9 || key == 13 ||
// Home and End
key == 35 || key == 36 ||
// left and right arrows
key == 37 || key == 39 ||
// Del and Ins
key == 46 || key == 45)
return true;
return false;
});
});
}
</script>
With the plug-in in place in your page or an external .js file you can now simply use a selector to apply it:
$(".numberinput").forceNumeric();
The plug-in basically goes through each selected element and hooks up a keydown() event handler. When a key is pressed the handler is fired and the keyCode of the event object is sent. Recall that jQuery normalizes the JavaScript Event object between browsers. The code basically white-lists a few key codes and rejects all others. It returns true to indicate the keypress is to go through or false to eat the keystroke and not process it which effectively removes it.
Simple and low tech, and it works without too much change of typical text box behavior.
The Voices of Reason
# re: Restricting Input in HTML Textboxes to Numeric Values
The example page is at http://www.manukalodgenz.com/js/
# re: Restricting Input in HTML Textboxes to Numeric Values
# re: Restricting Input in HTML Textboxes to Numeric Values
10.50
and
10,50
Depending on culture settings.
# re: Restricting Input in HTML Textboxes to Numeric Values
we used to have a separate js file which contains all the necessary activities like text only , number only, date diff etc. and using jquery bind to the textbox.
# re: Restricting Input in HTML Textboxes to Numeric Values
# re: Restricting Input in HTML Textboxes to Numeric Values
Definitely could do with additional characters though for separators, decimal points and negative number symbols. Will add that when I get a minute.
# re: Restricting Input in HTML Textboxes to Numeric Values
# Annoying.
# re: Restricting Input in HTML Textboxes to Numeric Values
Lot of comments that this won't solve all numeric entry problems and that's very true - it's not meant to. This is supposed to act as an input aid. You will still need to validate the final input for proper formatting etc. either client side or on the server.
# Good work
@Rick - sometimes, when users & the readers of form entries aren't computer literate, we do need to restrict what people can type, to limit confusion.
# re: Restricting Input in HTML Textboxes to Numeric Values
# re: Restricting Input in HTML Textboxes to Numeric Values
# re: Restricting Input in HTML Textboxes to Numeric Values
1. allow only one decimal separator
2. fix decimal places
var decSeparator =".";//or "," (function(jQuery) { function internalCheck(code, ch, key, v) { if (key==code) if (ch==decSeparator) { if (v.indexOf(decSeparator)!=-1) return false; } else { return false; } return true; } jQuery.fn.forceNumeric = function (options) { var opts = jQuery.extend({}, jQuery.fn.forceNumeric.defaults, options); return this.each(function () { var o = jQuery.meta ? jQuery.extend({}, opts, $this.data()) : opts; $(this).keydown(function (e) { var key = e.which || e.keyCode; if (!e.shiftKey && !e.altKey && !e.ctrlKey && // numbers key >= 48 && key <= 57 || // Numeric keypad key >= 96 && key <= 105 || // comma, period and minus, . on keypad ' key == 190 || key == 188 || key == 109 || key == 110 || key == 222 || // Backspace and Tab and Enter key == 8 || key == 9 || key == 13 || // Home and End key == 35 || key == 36 || // left and right arrows key == 37 || key == 39 || // Del and Ins key == 46 || key == 45) { var v=$(this).val(); var tmp =internalCheck(190,".",key,v); if (!tmp) return false; var tmp =internalCheck(188,",",key,v); if (!tmp) return false; return true; } else if (e.ctrlKey){ //ctrl-c ctrl-v ctrl-x if (key==67 || key==86 || key==90) return true; } return false; }); $(this).blur(function (e) { var v=jQuery.trim($(this).val()); if (v=='') { return; } if(o.fixDecimals!=-1) { var num = parseFloat(v); var numSix = num.toFixed(o.fixDecimals); $(this).val(numSix); } }); }); jQuery.fn.forceNumeric.defaults = { fixDecimals : -1 }; }; })(jQuery);
# re: Restricting Input in HTML Textboxes to Numeric Values
# re: Restricting Input in HTML Textboxes to Numeric Values
how i can restrict numbers and restrict ctrl-c,ctrl-c in textbox with jquery
# re: Restricting Input in HTML Textboxes to Numeric Values
Check for keycode 67 and e.ctrlKey set inside of keydown:
if (!e.ctrlKey && e.which == 67) return false; // cancel event bubbling
# re: Restricting Input in HTML Textboxes to Numeric Values
To process CTRL+X, this:
//ctrl-c ctrl-v ctrl-x if (key==67 || key==86 || key==90) return true;
should be this:
//ctrl-c ctrl-v ctrl-x if (key==67 || key==86 || key==88) return true;
Or I'm missing something?
# re: Restricting Input in HTML Textboxes to Numeric Values
Since people have so many different keyboard layouts, I would recommend never using the keyCode at all (unless perhaps for things like games, where you don't care what the actual character is). I would recommend instead the validation approach: let the user type whatever she likes, and fix the result upon validation (or when the input loses focus) by reading the actual content of the field, and using regular expressions.
Cheers.
# re: Restricting Input in HTML Textboxes to Numeric Values
say, I want to know if the input text included a <script>....</script>, how do I restrict it from users?
# re: Restricting Input in HTML Textboxes to Numeric Values
# re: Restricting Input in HTML Textboxes to Numeric Values
Is there a way to avoid user from pasting non-numeric values in textbox and allowing only numeric values to copy-paste.
If you have some code for this then kindly paste it. It will be really helpful.
Cheers,
Manoj
# re: Restricting Input in HTML Textboxes to Numeric Values
// 2 numeric digits
$('.numericField').mask('?99');
But this looks like a nice lighter alternative if you just need that functionality.