I am creating a web page where I have an input text field in which I want to allow only numeric characters like (0,1,2,3,4,5...9) 0-9.
How can I do this using jQuery?
I am creating a web page where I have an input text field in which I want to allow only numeric characters like (0,1,2,3,4,5...9) 0-9.
How can I do this using jQuery?
Note: This is an updated answer. Comments below refer to an old version which messed around with keycodes.
Try it yourself on JSFiddle.
There is no native jQuery implementation for this, but you can filter the input values of a text <input>
with the following inputFilter
plugin (supports Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, the caret position, different keyboard layouts, validity error message, and all browsers since IE 9):
// Restricts input for the set of matched elements to the given inputFilter function.
(function($) {
$.fn.inputFilter = function(callback, errMsg) {
return this.on("input keydown keyup mousedown mouseup select contextmenu drop focusout", function(e) {
if (callback(this.value)) {
// Accepted value
if (["keydown","mousedown","focusout"].indexOf(e.type) >= 0){
$(this).removeClass("input-error");
this.setCustomValidity("");
}
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty("oldValue")) {
// Rejected value - restore the previous one
$(this).addClass("input-error");
this.setCustomValidity(errMsg);
this.reportValidity();
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
} else {
// Rejected value - nothing to restore
this.value = "";
}
});
};
}(jQuery));
You can now use the inputFilter
plugin to install an input filter:
$(document).ready(function() {
$("#myTextBox").inputFilter(function(value) {
return /^\d*$/.test(value); // Allow digits only, using a RegExp
},"Only digits allowed");
});
Apply your preferred style to input-error class. Here's a suggestion:
.input-error{
outline: 1px solid red;
}
See the JSFiddle demo for more input filter examples. Also note that you still must do server side validation!
jQuery isn't actually needed for this, you can do the same thing with pure JavaScript as well. See this answer.
HTML 5 has a native solution with <input type="number">
(see the specification), but note that browser support varies:
step
, min
and max
attributes.e
and E
into the field. Also see this question.Try it yourself on w3schools.com.
keypress
eventhandler. For example: $('#nummer').keypress(function (event) { console.log('keypress: ' + event.which); if (!isNumber(event.which)) { event.preventDefault(); } }); function isNumber(characterCode) { var isNumber = false; if (characterCode >= 48 && characterCode <= 57) { isNumber = true; } return isNumber; }
–
Correggio event.keyCode == 40
for Up button –
Intendance Here is the function I use:
// Numeric only control handler
jQuery.fn.ForceNumericOnly =
function()
{
return this.each(function()
{
$(this).keydown(function(e)
{
var key = e.charCode || e.keyCode || 0;
// allow backspace, tab, delete, enter, arrows, numbers and keypad numbers ONLY
// home, end, period, and numpad decimal
return (
key == 8 ||
key == 9 ||
key == 13 ||
key == 46 ||
key == 110 ||
key == 190 ||
(key >= 35 && key <= 40) ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
});
});
};
You can then attach it to your control by doing:
$("#yourTextBoxName").ForceNumericOnly();
return this.each(function()
? –
Negrillo each
from return this.each(function()
is to allow multiple objects as HaggleLad said, and the return
part is to return the jQuery object back to the caller, to allow chaining such as $("input[type='text'").ForceNumericOnly().show()
–
Koumis key == 13 ||
to make sure Enter is allowed, for form submital and such –
Gleich Inline:
<input name="number" onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')">
Unobtrusive style (with jQuery):
$('input[name="number"]').keyup(function(e)
{
if (/\D/g.test(this.value))
{
// Filter non-digits from input value.
this.value = this.value.replace(/\D/g, '');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="number">
onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')"
. –
Gustafsson onkeyup="if (/^-?\d*$/.test(this.value)){ this.oldValue = this.value; } else { this.value = this.oldValue || ''; }"
. –
Gustafsson /[^0-9]|^0+(?!$)/g
to prevent leading series of zero. –
Irretentive onkeyup="if (isNaN(parseFloat(this.value))) { this.value = this.oldValue || ''; } else { this.oldValue = this.value; }"
. –
Gustafsson decimal
between 0.0
to 24.0
I am unable to let it enter the .
–
Dingdong You can use on input event like this:
$(document).on("input", ".numeric", function() {
this.value = this.value.replace(/\D/g,'');
});
But, what's this code privilege?
decimal
between 0.0
to 24.0
I am unable to let it enter the .
–
Dingdong this.value = Number(this.value.replace(/\D/g, ''));
–
Wieland You could just use a simple JavaScript regular expression to test for purely numeric characters:
/^[0-9]+$/.test(input);
This returns true if the input is numeric or false if not.
or for event keycode, simple use below :
// Allow: backspace, delete, tab, escape, enter, ctrl+A and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
var charValue = String.fromCharCode(e.keyCode)
, valid = /^[0-9]+$/.test(charValue);
if (!valid) {
e.preventDefault();
}
Short and sweet - even if this will never find much attention after 30+ answers ;)
$('#number_only').bind('keyup paste', function(){
this.value = this.value.replace(/[^0-9]/g, '');
});
Use JavaScript function isNaN,
if (isNaN($('#inputid').val()))
if (isNaN(document.getElementById('inputid').val()))
if (isNaN(document.getElementById('inputid').value))
Update: And here a nice article talking about it but using jQuery: Restricting Input in HTML Textboxes to Numeric Values
document.getElementById('inputid').val()
dude.. that's still jquery. .val()
is a jquery thing. use .value
–
Stereopticon decimal
between 0.0
to 24.0
I am unable to let it enter the .
–
Dingdong $(document).ready(function() {
$("#txtboxToFilter").keydown(function(event) {
// Allow only backspace and delete
if ( event.keyCode == 46 || event.keyCode == 8 ) {
// let it happen, don't do anything
}
else {
// Ensure that it is a number and stop the keypress
if (event.keyCode < 48 || event.keyCode > 57 ) {
event.preventDefault();
}
}
});
});
Source: http://snipt.net/GerryEng/jquery-making-textfield-only-accept-numeric-values
I use this in our internal common js file. I just add the class to any input that needs this behavior.
$(".numericOnly").keypress(function (e) {
if (String.fromCharCode(e.keyCode).match(/[^0-9]/g)) return false;
});
Why so complicated? You don't even need jQuery because there is a HTML5 pattern attribute:
<input type="text" pattern="[0-9]*">
The cool thing is that it brings up a numeric keyboard on mobile devices, which is way better than using jQuery.
Simpler one for me is
jQuery('.plan_eff').keyup(function () {
this.value = this.value.replace(/[^1-9\.]/g,'');
});
this.value.replace(/[^0-9\.]/g,'');
to include OP's requirements of 0-9 –
Sudd You can do the same by using this very simple solution
$("input.numbers").keypress(function(event) {
return /\d/.test(String.fromCharCode(event.keyCode));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="numbers" name="field_name" />
I referred to this link for the solution. It works perfectly!!!
decimal
between 0.0
to 24.0
I am unable to let it enter the .
–
Dingdong The pattern attribute in HTML5 specifies a regular expression that the element's value is checked against.
<input type="text" pattern="[0-9]{1,3}" value="" />
Note: The pattern attribute works with the following input types: text, search, url, tel, email, and password.
[0-9] can be replaced with any regular expression condition.
{1,3} it represents minimum of 1 and maximum of 3 digit can be entered.
decimal
between 0.0
to 24.0
I am unable to let it enter the .
–
Dingdong function suppressNonNumericInput(event){
if( !(event.keyCode == 8 // backspace
|| event.keyCode == 46 // delete
|| (event.keyCode >= 35 && event.keyCode <= 40) // arrow keys/home/end
|| (event.keyCode >= 48 && event.keyCode <= 57) // numbers on keyboard
|| (event.keyCode >= 96 && event.keyCode <= 105)) // number on keypad
) {
event.preventDefault(); // Prevent character input
}
}
decimal
between 0.0
to 24.0
I am unable to let it enter the .
–
Dingdong Here is two different approaches:
APPROACH 1:
$("#approach1").on("keypress keyup blur",function (e) {
$(this).val($(this).val().replace(/[^0-9\.]/g,''));
if ((e.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2>Numeric with decimal point</h2><br/>
<span>Enter Amount</span>
<input type="text" name="amount" id="approach1">
APPROACH 2:
$("#approach2").on("keypress keyup blur",function (event) {
$(this).val($(this).val().replace(/[^\d].+/, ""));
if ((event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2>Numeric without decimal point</h2><br/>
<span>Enter Amount</span>
<input type="text" name="amount" id="approach2">
Something fairly simple using jQuery.validate
$(document).ready(function() {
$("#formID").validate({
rules: {
field_name: {
numericOnly:true
}
}
});
});
$.validator.addMethod('numericOnly', function (value) {
return /^[0-9]+$/.test(value);
}, 'Please only enter numeric values (0-9)');
If have a smooth OneLiner:
<input type="text" onkeypress="return /[0-9]/i.test(event.key)" >
try it within html code it self like onkeypress and onpast
<input type="text" onkeypress="return event.charCode >= 48 && event.charCode <= 57" onpaste="return false">
I came to a very good and simple solution that doesn't prevent the user from selecting text or copy pasting as other solutions do. jQuery style :)
$("input.inputPhone").keyup(function() {
var jThis=$(this);
var notNumber=new RegExp("[^0-9]","g");
var val=jThis.val();
//Math before replacing to prevent losing keyboard selection
if(val.match(notNumber))
{ jThis.val(val.replace(notNumber,"")); }
}).keyup(); //Trigger on page load to sanitize values set by server
You can use this JavaScript function:
function maskInput(e) {
//check if we have "e" or "window.event" and use them as "event"
//Firefox doesn't have window.event
var event = e || window.event
var key_code = event.keyCode;
var oElement = e ? e.target : window.event.srcElement;
if (!event.shiftKey && !event.ctrlKey && !event.altKey) {
if ((key_code > 47 && key_code < 58) ||
(key_code > 95 && key_code < 106)) {
if (key_code > 95)
key_code -= (95-47);
oElement.value = oElement.value;
} else if(key_code == 8) {
oElement.value = oElement.value;
} else if(key_code != 9) {
event.returnValue = false;
}
}
}
And you can bind it to your textbox like this:
$(document).ready(function() {
$('#myTextbox').keydown(maskInput);
});
I use the above in production, and it works perfectly, and it is cross-browser. Furthermore, it does not depend on jQuery, so you can bind it to your textbox with inline JavaScript:
<input type="text" name="aNumberField" onkeydown="javascript:maskInput()"/>
Here is a quick solution I created some time ago. you can read more about it in my article:
http://ajax911.com/numbers-numeric-field-jquery/
$("#textfield").bind("keyup paste", function(){
setTimeout(jQuery.proxy(function() {
this.val(this.val().replace(/[^0-9]/g, ''));
}, $(this)), 0);
});
I think it will help everyone
$('input.valid-number').bind('keypress', function(e) {
return ( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) ? false : true ;
})
if(event.which!=8 && event.which!=0 && (event.which<48 || event.which>57) && (event.which<96 || event.which>105)) return;
–
Parvenu This seems unbreakable.
// Prevent NULL input and replace text.
$(document).on('change', 'input[type="number"]', function (event) {
this.value = this.value.replace(/[^0-9\.]+/g, '');
if (this.value < 1) this.value = 0;
});
// Block non-numeric chars.
$(document).on('keypress', 'input[type="number"]', function (event) {
return (((event.which > 47) && (event.which < 58)) || (event.which == 13));
});
Here is an answer that uses jQuery UI Widget factory. You can customize what characters are allowed easily.
$('input').numberOnly({
valid: "0123456789+-.$,"
});
That would allow numbers, number signs and dollar amounts.
$.widget('themex.numberOnly', {
options: {
valid : "0123456789",
allow : [46,8,9,27,13,35,39],
ctrl : [65],
alt : [],
extra : []
},
_create: function() {
var self = this;
self.element.keypress(function(event){
if(self._codeInArray(event,self.options.allow) || self._codeInArray(event,self.options.extra))
{
return;
}
if(event.ctrlKey && self._codeInArray(event,self.options.ctrl))
{
return;
}
if(event.altKey && self._codeInArray(event,self.options.alt))
{
return;
}
if(!event.shiftKey && !event.altKey && !event.ctrlKey)
{
if(self.options.valid.indexOf(String.fromCharCode(event.keyCode)) != -1)
{
return;
}
}
event.preventDefault();
});
},
_codeInArray : function(event,codes) {
for(code in codes)
{
if(event.keyCode == codes[code])
{
return true;
}
}
return false;
}
});
You would want to allow tab:
$("#txtboxToFilter").keydown(function(event) {
// Allow only backspace and delete
if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 ) {
// let it happen, don't do anything
}
else {
// Ensure that it is a number and stop the keypress
if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
event.preventDefault();
}
}
});
I wrote mine based off of @user261922's post above, slightly modified so you can select all, tab and can handle multiple "number only" fields on the same page.
var prevKey = -1, prevControl = '';
$(document).ready(function () {
$(".OnlyNumbers").keydown(function (event) {
if (!(event.keyCode == 8 // backspace
|| event.keyCode == 9 // tab
|| event.keyCode == 17 // ctrl
|| event.keyCode == 46 // delete
|| (event.keyCode >= 35 && event.keyCode <= 40) // arrow keys/home/end
|| (event.keyCode >= 48 && event.keyCode <= 57) // numbers on keyboard
|| (event.keyCode >= 96 && event.keyCode <= 105) // number on keypad
|| (event.keyCode == 65 && prevKey == 17 && prevControl == event.currentTarget.id)) // ctrl + a, on same control
) {
event.preventDefault(); // Prevent character input
}
else {
prevKey = event.keyCode;
prevControl = event.currentTarget.id;
}
});
});
This is why I recently wrote to accomplish this. I know this has already been answered but I'm leaving this for later uses.
This method only allows 0-9 both keyboard and numpad, backspaces, tab, left and right arrows (normal form operations)
$(".numbersonly-format").keydown(function (event) {
// Prevent shift key since its not needed
if (event.shiftKey == true) {
event.preventDefault();
}
// Allow Only: keyboard 0-9, numpad 0-9, backspace, tab, left arrow, right arrow, delete
if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105) || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46) {
// Allow normal operation
} else {
// Prevent the rest
event.preventDefault();
}
});
You can use the following code.
<input type="text" onkeypress="return event.charCode >= 48 && event.charCode <= 57">
You can try the HTML5 number input:
<input type="number" placeholder="enter the number" min="0" max="9">
This input tag element would now take value only between 0 to 9 as min attribute is set to 0 and max attribute is set to 9.
for more information on visit http://www.w3schools.com/html/html_form_input_types.asp
Just need to apply this method in Jquery and you can validate your textbox to just accept number only.
function IsNumberKeyWithoutDecimal(element) {
var value = $(element).val();
var regExp = "^\\d+$";
return value.match(regExp);
}
Try this solution here
Simple way to check that enter value is numeric is:
var checknumber = $('#textbox_id').val();
if(jQuery.isNumeric(checknumber) == false){
alert('Please enter numeric value');
$('#special_price').focus();
return;
}
I also would like to answer :)
$('.justNum').keydown(function(event){
var kc, num, rt = false;
kc = event.keyCode;
if(kc == 8 || ((kc > 47 && kc < 58) || (kc > 95 && kc < 106))) rt = true;
return rt;
})
.bind('blur', function(){
num = parseInt($(this).val());
num = isNaN(num) ? '' : num;
if(num && num < 0) num = num*-1;
$(this).val(num);
});
That's it...just numbers. :) Almost it can work just with the 'blur', but...
I wanted to help a little, and I made my version, the onlyNumbers
function...
function onlyNumbers(e){
var keynum;
var keychar;
if(window.event){ //IE
keynum = e.keyCode;
}
if(e.which){ //Netscape/Firefox/Opera
keynum = e.which;
}
if((keynum == 8 || keynum == 9 || keynum == 46 || (keynum >= 35 && keynum <= 40) ||
(event.keyCode >= 96 && event.keyCode <= 105)))return true;
if(keynum == 110 || keynum == 190){
var checkdot=document.getElementById('price').value;
var i=0;
for(i=0;i<checkdot.length;i++){
if(checkdot[i]=='.')return false;
}
if(checkdot.length==0)document.getElementById('price').value='0';
return true;
}
keychar = String.fromCharCode(keynum);
return !isNaN(keychar);
}
Just add in input tag "...input ... id="price" onkeydown="return onlyNumbers(event)"..." and you are done ;)
Need to make sure you have the numeric keypad and the tab key working too
// Allow only backspace and delete
if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9) {
// let it happen, don't do anything
}
else {
// Ensure that it is a number and stop the keypress
if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105)) {
}
else {
event.preventDefault();
}
}
You can use HTML5 validation on your text inputs by adding a pattern. No need to manually validate with regex or keyCodes.
<input type="text" pattern="[0-9.]+" />
$("input[type=text][pattern]").on("input", function () {
if (!this.checkValidity())
this.value = this.value.slice(0, -1);
});
Possible, but not as simple for inputs [type=number]...
The problem with [type="number"] is that we cannot only remove the invalid character at the end. The User Agents return an empty string whenever the input is invalid.
From the W3C HTML5 spec:
If the value of the element is not a valid floating point number, then set it to the empty string instead.
https://dev.w3.org/html5/spec-LC/number-state.html#number-state
This means we need a way to store the previous input value by hand.
So for number inputs, the solution would look like this:
$("input[type=number], input[type=text][pattern]").on("input", function () {
if (!this.checkValidity())
this.value = $(this).data("current-valid") || "";
else
$(this).data("current-valid", this.value);
});
Unfortunately, this will not work on IE and EDGE. We need to resort to the pattern solution above for these browsers. However, you can still use number inputs with this simple polyfill.
$("input[type=number]").attr("type", "text").attr("pattern", "[0-9.]+");
If you have to solve diacritics and special characters, try to use this:
$(this).on( 'keypress', function( e )
{
// Ensure that it is a number and stop the keypress
if (e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) {
e.preventDefault();
}
});
There is an incredible compatibility issue with using keystrokes to detect the character pressed... see quirksmode to know more about that.
I would suggest using keyup to create your filter because then you have the $(element).val() method you can use to evaluate actual universal characters.
Then you can filter out any NON digits using a regex like:
replace(/[^0-9]/g,'');
This takes care of all issues like shift and paste problems because there is always a keyup and so the value will always be evaluated (unless javascript is turned off).
So... to turn this into JQuery... Here is a little unfinished plugin I'm writing, it is called inputmask and will support more masks when finished. For now it has the digits mask working.
Here it goes...
/**
* @author Tom Van Schoor
* @company Tutuka Software
*/
(function($) {
/**
* @param {Object}
* $$options options to override settings
*/
jQuery.fn.inputmask = function($$options) {
var $settings = $.extend( {}, $.fn.inputmask.defaults, $$options);
return this.each(function() {
// $this is an instance of the element you call the plug-in on
var $this = $(this);
/*
* This plug-in does not depend on the metadata plug-in, but if this
* plug-in detects the existence of the metadata plug-in it will
* override options with the metadata provided by that plug-in. Look at
* the metadata plug-in for more information.
*/
// o will contain your defaults, overruled by $$options,
// overruled by the meta-data
var o = $.metadata ? $.extend( {}, $settings, $this.metadata()) : $settings;
/*
* if digits is in the array 'validators' provided by the options,
* stack this event handler
*/
if($.inArray('digits', o.validators) != -1) {
$this.keyup(function(e) {
$this.val(stripAlphaChars($this.val()));
});
}
/*
* There is no such things as public methods in jQuery plug-ins since
* there is no console to perform commands from a client side point of
* view. Typically only private methods will be fired by registered
* events as on-click, on-drag, etc... Those registered events could be
* seen as public methods.
*/
// private method
var stripAlphaChars = function(string) {
var str = new String(string);
str = str.replace(/[^0-9]/g, '');
return str;
}
});
};
// static public functions
//jQuery.fn.inputmask.doSomething = function(attr) {
//};
// static public members
//jQuery.fn.inputmask.someStaticPublicMember;
// some default settings that can be overridden by either $$options or
// metadata
// If you need callback functions for the plug-in, this is where they get
// set
jQuery.fn.inputmask.defaults = {
validators : []
};
})(jQuery);
To use it just do:
$('#someElementId').inputmask({
validators: ['digits','someOtherNotYetImplementedValidator']
});
The 'someOtherNotYetImplementedValidator' is just there to show how this can be expanded for extra future masks/validators. You can add it or leave it out, it doesn't break anything ;-)
Appologies for the extra clutter of comments, I'm using a template I created for the guys here at work.
Hope this helps, Cheers
onkeyup="this.value=this.value.replace(/\D/g,'')"
. –
Gustafsson $("#inputfield").keypress(function(e) { if (e.which < 48 || e.which > 57) e.preventDefault(); });
–
Aerugo if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')
so the value is only changed (and the cursor jumps to the end) if there is an invalid character. That way, you can still use arrow keys. You can also enter numbers in the middle without the cursor moving. –
Gustafsson Updated solution for a better user experience, that addresses the copy+paste issue and replaces the deprecated keyCode attribute:
HTML
<input type="tel">
jQuery
$('[type=tel]').on('change', function(e) {
$(e.target).val($(e.target).val().replace(/[^\d]/g, ''))
})
$('[type=tel]').on('keypress', function(e) {
keys = ['0','1','2','3','4','5','6','7','8','9']
return keys.indexOf(event.key) > -1
})
Details:
First of all, input types:
number
shows up/down arrows shrinking the actual input space, I find them ugly and are only useful if the number represents a quantity (things like phones, area codes, IDs... don't need them)
tel
provides similar browser validations of number without arrows
Using [number / tel] also helps showing numeric keyboard on mobile devices.
For the JS validation I ended up needing 2 functions, one for the normal user input (keypress) and the other for a copy+paste fix (change), other combinations would give me a terrible user experience.
I use the more reliable KeyboardEvent.key instead of the now deprecated KeyboardEvent.charCode
And depending of your browser support you can consider using Array.prototype.includes() instead of the poorly named Array.prototype.indexOf() (for true / false results)
Here is way with regular expression:
$('input').bind('keypress', function (event) {
var regex = new RegExp("^[0-9]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
https://jsfiddle.net/astrapi69/qbk2vjty/1/
And you can change the regular expression to anything else if you want to restrict other characters then numbers.
I had a problem with the top-answer. It doesn't include the numerical keypad and if one presses shift+number the special-signs shouldn't be displayed either.. but this solution doesn't take care of it.
The best link I've found in this thread was this: http://www.west-wind.com/weblog/posts/2011/Apr/22/Restricting-Input-in-HTML-Textboxes-to-Numeric-Values
I'm new to stackoverflow so I don't know if I can just edit the better solution into the top-post.
This jQuery code filters out characters typed while Shift, Ctrl or Alt is held down.
$('#AmountText').keydown(function (e) {
if (e.shiftKey || e.ctrlKey || e.altKey) { // if shift, ctrl or alt keys held down
e.preventDefault(); // Prevent character input
} else {
var n = e.keyCode;
if (!((n == 8) // backspace
|| (n == 46) // delete
|| (n >= 35 && n <= 40) // arrow keys/home/end
|| (n >= 48 && n <= 57) // numbers on keyboard
|| (n >= 96 && n <= 105)) // number on keypad
) {
e.preventDefault(); // Prevent character input
}
}
});
To elaborate a little more on answer #3 I'd do the following (NOTE: still does not support paste oprations through keyboard or mouse):
$('#txtNumeric').keypress(
function(event) {
//Allow only backspace and delete
if (event.keyCode != 46 && event.keyCode != 8) {
if (!parseInt(String.fromCharCode(event.which))) {
event.preventDefault();
}
}
}
);
Many people here are using keycode property which is not easy to remember. If you do not have a locale issues then you can simply use key which is actually the input that user types.
See this Fiddle
$("#txt").on("keypress",function(e){
console.log("Entered Key is " + e.key);
switch (e.key)
{
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
case "0":
case "Backspace":
return true;
break;
case ".":
if ($(this).val().indexOf(".") == -1) //Checking if it already contains decimal. You can Remove this condition if you do not want to include decimals in your input box.
{
return true;
}
else
{
return false;
}
break;
default:
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Enter Value
<input id="txt" type="text" />
issue then see the following simple code.
Please note that this example also contains validation for decimal entry.
As per this question it is not required so you can simply remove the case "." to remove entry of decimal.
You can use HTML5 input type number to restrict only number entries:
<input type="number" name="someid" />
This will work only in HTML5 complaint browser. Make sure your html document's doctype is:
<!DOCTYPE html>
For general purpose, you can have JS validation as below:
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
<input type="someid" name="number" onkeypress="return isNumberKey(event)"/>
If you want to allow decimals replace the "if condition" with this:
if (charCode > 31 && (charCode != 46 &&(charCode < 48 || charCode > 57)))
Source: HTML Text Input allow only Numeric input
JSFiddle demo: http://jsfiddle.net/Gagan_Gami/nSjy7/333/
add below code in document.ready
$('.class of text box').keyup(function ()
{
this.value = this.value.replace(/[^0-9]/g, '');
});
It may be overkill for what you are looking for, yet I suggest a jQuery plugin called autoNumeric() - it is great!
You can limit to only numbers, decimal precision, max / min values and more.
The SIMPLEST solution to this is within your html form code add:
<input type="number"
If it's a php form then add:
$data = array(
'type' => 'number',
Both of these
None of the answers worked in my case so I made a little change in the accepted answer to make it work for Dynamically added elements.
Enjoy :
var inputFilter = function (elem, cb) {
/*
* /^-?\d*$/ restricts input to integer numbers
* /^\d*$/ restricts input to unsigned integer numbers
* /^[0-9a-f]*$/i restricts input to hexadecimal numbers
* /^-?\d*[.,]?\d*$/ restricts input to floating point numbers (allowing both . and , as decimal separator)
* /^-?\d*[.,]?\d{0,2}$/ restricts input to currency values (i.e. at most two decimal places)
*/
bdy.on('input keydown keyup mousedown mouseup select contextmenu drop', elem, function () {
if (cb(this.value)) {
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty('oldValue')) {
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
}
});
};
Usage :
inputFilter('#onlyDigitsInput', function (val) {
return /^\d*$/.test(val);
});
This answer was perfect, but we can even make it better and more powerful by combining it with the jQuery.Validation plugin.
By using the number() method, we can develop something like this:
$('.numberOnly').keydown(function (event) {
if ((!event.shiftKey && !event.ctrlKey && !event.altKey) &&
((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105)))
// 0-9 or numpad 0-9, disallow shift, ctrl, and alt
{
// check textbox value now and tab over if necessary
}
else if (event.keyCode != 8 && event.keyCode != 13 && event.keyCode != 46 && event.keyCode != 37
&& event.keyCode != 39 && event.keyCode != 9 && event.keyCode != 109
&& event.keyCode != 189 && event.keyCode != 110 && event.keyCode != 190)
// not backsapce (8), enter (13), del (46), left arrow (37), right arrow (39), tab (9), negetive sign (- : 109, 189), or point (. : 110, 190)
{
event.preventDefault();
}
// else the key should be handled normally
});
// _____________________________________________
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
// _____________________________________________
$(document).ready(function(){
$('#myFormId').validate({
rules: {
field: {
required: true,
number: true
}
}
});
});
So, any Textbox in the "#myFormId" form, with "numberOnly" class, accept only number including decimal, float, and even negative number. Voila :)
PS: In my case, for some reason I used jQuery.validator.addMethod() instead of .validate():
jQuery.validator.addMethod("numberOnly", function (value, element) {
var result = !isNaN(value);
return this.optional(element) || result;
}, jQuery.format("Please enter a valid number."));
(it works fine inside my ASP.NET MVC 3 project + unobtrusive JavaScript validation, hooooooooray!)
/**
Makes the textbox to accept only numeric input
*/
(function($) {
$.fn.allowOnlyNumeric = function() {
/**
The interval code is commented as every 250 ms onchange of the textbox gets fired.
*/
// var createDelegate = function(context, method) {
// return function() { method.apply(context, arguments); };
// };
/**
Checks whether the key is only numeric.
*/
var isValid = function(key) {
var validChars = "0123456789";
var validChar = validChars.indexOf(key) != -1;
return validChar;
};
/**
Fires the key down event to prevent the control and alt keys
*/
var keydown = function(evt) {
if (evt.ctrlKey || evt.altKey) {
evt.preventDefault();
}
};
/**
Fires the key press of the text box
*/
var keypress = function(evt) {
var scanCode;
//scanCode = evt.which;
if (evt.charCode) { //For ff
scanCode = evt.charCode;
}
else { //For ie
scanCode = evt.keyCode;
}
if (scanCode && scanCode >= 0x20 /* space */) {
var c = String.fromCharCode(scanCode);
if (!isValid(c)) {
evt.preventDefault();
}
}
};
/**
Fires the lost focus event of the textbox
*/
var onchange = function() {
var result = [];
var enteredText = $(this).val();
for (var i = 0; i < enteredText.length; i++) {
var ch = enteredText.substring(i, i + 1);
if (isValid(ch)) {
result.push(ch);
}
}
var resultString = result.join('');
if (enteredText != resultString) {
$(this).val(resultString);
}
};
//var _filterInterval = 250;
//var _intervalID = null;
//var _intervalHandler = null;
/**
Dispose of the textbox to unbind the events.
*/
this.dispose = function() {
$(this).die('change', onchange);
$(this).die('keypress', keypress);
$(this).die('keydown', keydown);
//window.clearInterval(_intervalHandler);
};
$(this).live('change', onchange);
$(this).live('keypress', keypress);
$(this).live('keydown', keydown);
//_intervalHandler = createDelegate(this, onchange);
//_intervalID = window.setInterval(_intervalHandler, _filterInterval);
}
})(jQuery);
The above $ plugin is written from the AjaxControlToolkit filter textbox extender.js.
However one behavior is not borrowed from the AjaxControlToolkit is that when the user copies and pastes any non-numeric value then the onchange event fires up and text box eats up the values. I went through the code and found out for this onchange was called after every 250ms, which is a performance hit, hence commented that part.
Allow single decimal and numeric only, single line
$(document).on("input", "#bill_amount", function() {
this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');
// Remove extra dots by (/(\..*)\./g, '$1');
});
This would maintain the previous value in case a non-numeric character is added.
$(document).on('input', '.digit-input', function() {
var prevVal = $(this).attr('ov') ? $(this).attr('ov') : '';
var newVal = this.value.replace(/[^0-9]/g, '');
this.value = newVal != '' ? newVal : prevVal;
$(this).attr('ov', this.value);
});
$(document).on('input', '.digit-input', function() {
var prevVal = $(this).attr('ov') ? $(this).attr('ov') : '';
var newVal = this.value.replace(/[^0-9]/g, '');
this.value = newVal != '' ? newVal : prevVal;
$(this).attr('ov', this.value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="digit-input">
$(document).on("keypress", ".classname", function(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
});
There are so many good answers to doing it with java Script or jQuery here.
I will add a very easy way to archive this using just HTML5.
<input type="number" name="quantity" min="0" max="9">
This is what I use to validate number inputs for integer or float values (unobtrusive style with jQuery):
$('input[name="number"]').keyup(function(e) {
var float = parseFloat($(this).attr('data-float'));
/* 2 regexp for validating integer and float inputs *****
> integer_regexp : allow numbers, but do not allow leading zeros
> float_regexp : allow numbers + only one dot sign (and only in the middle of the string), but do not allow leading zeros in the integer part
*************************************************************************/
var integer_regexp = (/[^0-9]|^0+(?!$)/g);
var float_regexp = (/[^0-9\.]|^\.+(?!$)|^0+(?=[0-9]+)|\.(?=\.|.+\.)/g);
var regexp = (float % 1 === 0) ? integer_regexp : float_regexp;
if (regexp.test(this.value)) {
this.value = this.value.replace(regexp, '');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" data-float="1" id="number" name="number" placeholder="integer">
<input type="text" data-float="0.1" id="number" name="number" placeholder="float">
put a class in input text and name it only_numbers
put the jquery code in the page
$(document).ready(function() {
$('.only_numbers').keyup(function() {
var numbers = $(this).val();
$(this).val(numbers.replace(/\D/, ''));
});
});
have fun :-)
function validate_profile(frmid) {
var form = $('#' + frmid);
var error = $('.alert-danger', form);
var success = $('.alert-success', form);
form.validate({
errorElement: 'span', //default input error message container
errorClass: 'help-block', // default input error message class
focusInvalid: true, // do not focus the last invalid input
ignore: "",
rules: {
contact_no: {
required: true,
minlength: 10,
maxlength: 10,
number: true
}, email_id: {
required: true,
email: true
}
},
invalidHandler: function (event, validator) { //display error alert on form submit
success.hide();
error.show();
Metronic.scrollTo(error, -7000);
},
highlight: function (element) { // hightlight error inputs
$(element)
.closest('.form-group').addClass('has-error'); // un set error class to the control group
$(element)
.closest('.form-group').removeClass('has-success'); // set success class to the control group
},
unhighlight: function (element) { // revert the change done by hightlight
$(element)
.closest('.form-group').removeClass('has-error'); // un set error class to the control group
$(element)
.closest('.form-group').addClass('has-success'); // set success class to the control group
error.hide();
},
success: function (label) {
label.closest('.form-group').removeClass('has-error');
label.closest('.form-group').addClass('has-success');
},
submitHandler: function (form) {
success.show();
error.hide();
form.submit();
}
});
}
I have combined all the answers in one and come up with the following code:
jQuery('#input_id', function(e){
// Allow: backspace, delete, tab, escape, enter
if (jQuery.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode === 65 && e.ctrlKey === true) ||
// Allow: Ctrl+C
(e.keyCode === 67 && e.ctrlKey === true) ||
// Allow: Ctrl+X
(e.keyCode === 88 && e.ctrlKey === true) ||
// Disallow several dots (allow 190 only if no dots found)
(e.keyCode === 190 && jQuery(this).val().indexOf('.') == -1) ||
// Bug in some Android devices where it is always 229
(e.keyCode === 229) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 40)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
In addition the form should have autocomplete="off"
. Without this option you might have issues with auto-complete algorithms on mobile devices.
Use below simple jQuery to allow only numeric characters in a tetbox. You do not need to filter all the special characters manually so there is no danger of missing some special char. This will allow only numbers 0-9: (Place below code in document ready and change the class name as per your numeric text fields class name.)
//Event of data being keyed in to textbox with class="numericField".
$(".numericField").keyup(function() {
// Get the non Numeric char that was enetered
var nonNumericChars = $(this).val().replace(/[0-9]/g, '');
// Now set the value in text box
$(this).val( $(this).val().replace(nonNumericChars, ''));
});
Refactored the accepted answer so that comments no longer need to used because I hate comments. Also this is easier to test with jasmine.
allowBackspaceDeleteTabEscapeEnterPress: function(event){
return ($.inArray(event.keyCode, [46, 8, 9, 27, 13, 190]) >= 0);
},
allowContorlAPress: function(event){
return (event.keyCode == 65 && event.ctrlKey === true)
},
allowHomeEndLeftRightPress: function(event){
return (event.keyCode >= 35 && event.keyCode <= 39)
},
theKeyPressedIsEditRelated: function (event) {
return (this.allowBackspaceDeleteTabEscapeEnterPress(event)
|| this.allowContorlAPress(event)
|| this.allowHomeEndLeftRightPress(event));
},
isNotFromTheNumKeyPad: function (event) {
return (event.keyCode < 96 || event.keyCode > 105);
},
isNotFromTopRowNumberKeys: function (event) {
return (event.keyCode < 48 || event.keyCode > 57);
},
theKeyIsNonNumeric: function (event) {
return (event.shiftKey
|| (this.isNotFromTopRowNumberKeys(event)
&& this.isNotFromTheNumKeyPad(event)));
},
bindInputValidator: function(){
$('.myinputclassselector').keydown(function (event) {
if(this.validateKeyPressEvent(event)) return false;
});
},
validateKeyPressEvent: function(event){
if(this.theKeyPressedIsEditRelated(event)){
return;
} else {
if (this.theKeyIsNonNumeric(event)) {
event.preventDefault();
}
}
}
$(document).ready(function()
{
$("#textBoxId").bind("change",checkInput);
});
function checkInput()
{
// check if $('#textBoxId').val() is under your constraints
// then change its value, removing the last character
// since this event will be called each time you
// type a character
}
Check if decimal point already used:-
// Stop: Multiple decimal points
if((e.keyCode == 190 || e.keyCode == 110) && ((this.value).indexOf(".") >= 0))
e.preventDefault();
Another approach is below. This will take care of pasting also. [it is for alpha-numeric validation]
//Input Validation
var existingLogDescription = "";
$('.logDescription').keydown(function (event) {
existingLogDescription = this.value;
});
$('.logDescription').keyup(function () {
if (this.value.match(/[^a-zA-Z0-9 ]/g)) {
alert("Log Description should contain alpha-numeric values only");
this.value = this.value.replace(/[^a-zA-Z0-9 ]/g, '');
this.value = existingLogDescription;
}
});
I'm using in this form. Seems correct to me allow keys like home, end, shift and ctrl, with the drawback of the user to can print special chars:
$("#busca_cep").keydown(function(event) {
if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 13 || event.keyCode == 16 || event.keyCode == 36 || event.keyCode == 35) {
if (event.keyCode == 13) {
localiza_cep(this.value);
}
} else {
if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
event.preventDefault();
}
}
});
I recommend to check event.metaKey as well. If that's set to true, the user might be doing something like cmd-A to select all the text in the field. You should allow that too.
jQuery("#no_of").keypress(function(event){
//Allow only backspace and delete
if (event.keyCode != 46 && event.keyCode != 8) {
if (!parseInt(String.fromCharCode(event.which))) {
event.preventDefault();
}
}
});
jQuery("#no_of").keyup(function(e){
var temp_s= jQuery("#no_of").val();
var multiply_val= temp_s*10;
jQuery("#ex-r").html(multiply_val);
});
Use the jquery numeric value. Below function allows for decimal and numeric values.
Example:
$("#inputId").numeric({ allow: "." });
function Numbers(e)
{
if($.browser.msie)
{
if(e.keyCode > 47 && e.keyCode < 58)
return true;
else
return false;
}
else
{
if((e.charCode > 47 && e.charCode < 58) || (e.charCode == 0))
return true;
else
return false;
}
}
I hope this will work on all browsers.
© 2022 - 2024 — McMap. All rights reserved.
<input pattern="[0-9]+" />
. I prefer this method because most browsers change the style of the input field when<input type="number" />
– Whichsoever