Input Field, Only Numbers Jquery/js
Solution 1:
Try this:
$("#num").keypress(function (e){
var charCode = (e.which) ? e.which : e.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
returnfalse;
}
});
Values 48 through 57 represent the digits 0-9.
Solution 2:
Never do this. A user can update a textbox without pressing the key. He can copy paste, drag. some text.
Also this will be irritating to the user.
Just display a label nect to the filed saying that this accepts only numbers. And then
Validate your code at submission
Solution 3:
Comparing to the current best answer this code is more user-friendly - it allows usage of arrows, backspace, delete and other keys/combinations:
// Ensures that it is a number and stops the key press
$('input[name="number"]').keydown(function(event) {
if (!(!event.shiftKey //Disallow: any Shift+digit combination
&& !(event.keyCode < 48 || event.keyCode > 57) //Disallow: everything but digits
|| !(event.keyCode < 96 || event.keyCode > 105) //Allow: numeric pad digits
|| event.keyCode == 46// Allow: delete
|| event.keyCode == 8// Allow: backspace
|| event.keyCode == 9// Allow: tab
|| event.keyCode == 27// Allow: escape
|| (event.keyCode == 65 && (event.ctrlKey === true || event.metaKey === true)) // Allow: Ctrl+A
|| (event.keyCode == 67 && (event.ctrlKey === true || event.metaKey === true)) // Allow: Ctrl+C//Uncommenting the next line allows Ctrl+V usage, but requires additional code from you to disallow pasting non-numeric symbols//|| (event.keyCode == 86 && (event.ctrlKey === true || event.metaKey === true)) // Allow: Ctrl+Vpasting
|| (event.keyCode >= 35 && event.keyCode <= 39) // Allow: Home, End
)) {
event.preventDefault();
}
});
Notes:
The event.metaKey === true
is required for Mac users (thanks RyanM for noticing this).
Also if you uncomment Ctrl+V sequence you will need to write additional code for checking pasted text (disallow non-numeric symbols).
Solution 4:
Here is my solution:
functionInputValidator(input, validationType, validChars) {
if (input === null || input.nodeType !== 1 || input.type !== 'text' && input.type !== 'number')
throw ('Please specify a valid input');
if (!(InputValidator.ValidationType.hasOwnProperty(validationType) || validationType))
throw'Please specify a valid Validation type';
input.InputValidator = this;
input.InputValidator.ValidCodes = [];
input.InputValidator.ValidCodes.Add = function (item) {
this[this.length] = item;
};
input.InputValidator.ValidCodes.hasValue = function (value, target) {
var i;
for (i = 0; i < this.length; i++) {
if (typeof (target) === 'undefined') {
if (this[i] === value)
returntrue;
}
else {
if (this[i][target] === value)
returntrue;
}
}
returnfalse;
};
var commandKeys = {
'backspace': 8,
'tab': 9,
'enter': 13,
'shift': 16,
'ctrl': 17,
'alt': 18,
'pause/break': 19,
'caps lock': 20,
'escape': 27,
'page up': 33,
'page down': 34,
'end': 35,
'home': 36,
'left arrow': 37,
'up arrow': 38,
'right arrow': 39,
'down arrow': 40,
'insert': 45,
'delete': 46,
'left window key': 91,
'right window key': 92,
'select key': 93,
/*creates Confusion in IE *///'f1': 112,//'f2': 113,//'f3': 114,//'f4': 115,//'f5': 116,//'f6': 117,//'f7': 118,//'f8': 119,//'f9': 120,//'f10': 121,//'f11': 122,//'f12': 123,'num lock': 144,
'scroll lock': 145,
};
commandKeys.hasValue = function (value) {
for (var a inthis) {
if (this[a] === value)
returntrue;
}
returnfalse;
};
functiongetCharCodes(arrTarget, chars) {
for (var i = 0; i < chars.length; i++) {
arrTarget.Add(chars[i].charCodeAt(0));
}
}
functiontriggerEvent(name, element) {
if (document.createEventObject) {
// dispatch for IEvar evt = document.createEventObject();
return element.fireEvent('on' + name, evt)
}
else {
// dispatch for firefox + othersvar evt = document.createEvent("HTMLEvents");
evt.initEvent(name, true, true); // event type,bubbling,cancelablereturn !element.dispatchEvent(evt);
}
}
if (validationType == InputValidator.ValidationType.Custom) {
if (typeof (validChars) === 'undefined')
throw'Please add valid characters';
getCharCodes(input.InputValidator.ValidCodes, validChars);
}
elseif (validationType == InputValidator.ValidationType.Decimal) {
getCharCodes(input.InputValidator.ValidCodes, '0123456789.');
}
elseif (validationType == InputValidator.ValidationType.Numeric) {
getCharCodes(input.InputValidator.ValidCodes, '0123456789');
}
input.InputValidator.ValidateChar = function (c) {
returnthis.ValidCodes.hasValue(c.charCodeAt(0));
}
input.InputValidator.ValidateString = function (s) {
var arr = s.split('');
for (var i = 0; i < arr.length; i++) {
if (!this.ValidateChar(arr[i])) {
arr[i] = '';
}
}
return arr.join('');
}
functionbindEvent(el, eventName, eventHandler) {
if (el.addEventListener) {
el.addEventListener(eventName, eventHandler, false);
} elseif (el.attachEvent) {
el.attachEvent('on' + eventName, eventHandler);
}
}
functiongetCaretPosition(i) {
if (!i) return;
if ('selectionStart'in i) {
return i.selectionStart;
}
else {
if (document.selection) {
var sel = document.selection.createRange();
var selLen = document.selection.createRange().text.length;
sel.moveStart('character', -i.value.length);
return sel.text.length - selLen;
}
}
}
functionsetCursor(node, pos) {
var node = (typeof (node) === "string" || node instanceofString) ? document.getElementById(node) : node;
if (!node) {
returnfalse;
}
elseif (node.createTextRange) {
var textRange = node.createTextRange();
textRange.collapse(true);
textRange.moveEnd(pos);
textRange.moveStart(pos);
textRange.select();
returntrue;
} elseif (node.setSelectionRange) {
node.setSelectionRange(pos, pos);
returntrue;
}
returnfalse;
}
functionvalidateActive() {
if (input.isActive) {
var pos = getCaretPosition(input);
var arr = input.value.split('');
for (var i = 0; i < arr.length; i++) {
if (!this.ValidateChar(arr[i])) {
arr[i] = '';
if (pos > i)
pos--;
}
}
console.log('before : ' + input.value);
input.value = arr.join('');
console.log('after : ' + input.value, input);
setCursor(input, pos);
setTimeout(validateActive, 10);
}
}
bindEvent(input, 'keypress', function (e) {
var evt = e || window.event;
var charCode = evt.which || evt.keyCode;
if (!input.InputValidator.ValidCodes.hasValue(charCode) && !commandKeys.hasValue(charCode)) {
if (evt.preventDefault) {
evt.preventDefault();
evt.stopPropagation();
}
returnfalse;
}
});
bindEvent(input, 'keyup', function (e) {
var evt = e || window.event;
var charCode = evt.which || evt.keyCode;
if (!input.InputValidator.ValidCodes.hasValue(charCode) && !commandKeys.hasValue(charCode)) {
if (evt.preventDefault) {
evt.preventDefault();
evt.stopPropagation();
}
returnfalse;
}
});
bindEvent(input, 'change', function (e) {
var dt = input.value;
input.value = input.InputValidator.ValidateString(input.value);
if (input.value !== dt)
triggerEvent('change', input);
});
bindEvent(input, 'blur', function (e) {
var dt = input.value;
input.value = input.InputValidator.ValidateString(input.value);
input.isActive = false;
if (input.value !== dt)
triggerEvent('blur', input);
});
bindEvent(input, 'paste', function (e) {
var evt = e || window.event;
var svt = input.value;
if (evt && evt.clipboardData && evt.clipboardData.getData) {// Webkit - get data from clipboard, put into editdiv, cleanup, then cancel eventif (/text\/html/.test(evt.clipboardData.types)) {
var dt = evt.clipboardData.getData('text/html');
input.value = input.InputValidator.ValidateString(dt);
if (input.value !== dt)
triggerEvent('change', input);
}
elseif (/text\/plain/.test(e.clipboardData.types)) {
var dt = evt.clipboardData.getData('text/plain');
input.value = input.InputValidator.ValidateString(dt);
if (input.value !== dt)
triggerEvent('change', input);
}
else {
input.value = '';
}
waitforpastedata(input, svt);
if (e.preventDefault) {
e.stopPropagation();
e.preventDefault();
}
returnfalse;
}
else {// Everything else - empty editdiv and allow browser to paste content into it, then cleanup
input.value = '';
waitforpastedata(input, svt);
returntrue;
}
});
bindEvent(input, 'select', function (e) {
var evt = e || window.event;
if (evt.preventDefault) {
evt.preventDefault();
evt.stopPropagation();
}
returnfalse;
});
bindEvent(input, 'selectstart', function (e) {
var evt = e || window.event;
if (evt.preventDefault) {
evt.preventDefault();
evt.stopPropagation();
}
returnfalse;
});
/* no need to validate wile active,
removing F keys fixed IE compatability*///bindEvent(input, 'fucus', function (e) {// input.isActive = true;// validateActive();//});//validate current value of the textbox
{
var dt = input.value;
input.value = input.InputValidator.ValidateString(input.value);
//trigger event to indicate value has changedif (input.value !== dt)
triggerEvent('change', input);
}
functionwaitforpastedata(elem, savedcontent) {
if (elem.value !== '') {
var dt = input.value;
elem.value = elem.InputValidator.ValidateString(elem.value);
if (input.value !== dt)
triggerEvent('change', input);
}
else {
var that = {
e: elem,
s: savedcontent
}
that.callself = function () {
waitforpastedata(that.e, that.s)
}
setTimeout(that.callself, 10);
}
}
}
InputValidator.ValidationType = new (function (types) {
for (var i = 0; i < types.length; i++) {
this[types[i]] = types[i];
}
})(['Numeric', 'Custom', 'Decimal']);
To apply it to an input, do the following :
newInputValidator(document.getElementById('txtValidate'), InputValidator.ValidationType.Decimal);/* Numeric or Custom */
If you specify Custom as the validation type you have to specify the valid characters. eg :
newInputValidator(document.getElementById('txtValidate'), InputValidator.ValidationType.Custom,'1234abc');
Solution 5:
Here's my code:
$("Input.onlyNumbersInput").live('input', function (event) {
$(this).val($(this).val().replace(/[^0-9]/g, ''));
});
Using "live('input')" event will make the function replace any character that is not a digit, which the user input, WITHOUT the user see the character.
If you use "onkeyup" event, the user will see the character for few miliseconds, which is not cool.
Post a Comment for "Input Field, Only Numbers Jquery/js"