I have a input field where i only wish users to type numbers
html: <input id="num" type="text" name="page" size="4" value="" />
jquery/ js:
$("#num").keypress(function (e){
if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)){
return false;
}
});
hope someone can help me.
btw: I'm not interesting in a larger jquery plugin to make the function work. (I have found some jquery-plugins , but there must be som other ways to fix it, with a smaller code)
Try this:
$("#num").keypress(function (e){
var charCode = (e.which) ? e.which : e.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
});
Values 48 through 57 represent the digits 0-9.
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
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).
Here is my solution:
function InputValidator(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)
return true;
}
else {
if (this[i][target] === value)
return true;
}
}
return false;
};
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 in this) {
if (this[a] === value)
return true;
}
return false;
};
function getCharCodes(arrTarget, chars) {
for (var i = 0; i < chars.length; i++) {
arrTarget.Add(chars[i].charCodeAt(0));
}
}
function triggerEvent(name, element) {
if (document.createEventObject) {
// dispatch for IE
var evt = document.createEventObject();
return element.fireEvent('on' + name, evt)
}
else {
// dispatch for firefox + others
var evt = document.createEvent("HTMLEvents");
evt.initEvent(name, true, true); // event type,bubbling,cancelable
return !element.dispatchEvent(evt);
}
}
if (validationType == InputValidator.ValidationType.Custom) {
if (typeof (validChars) === 'undefined')
throw 'Please add valid characters';
getCharCodes(input.InputValidator.ValidCodes, validChars);
}
else if (validationType == InputValidator.ValidationType.Decimal) {
getCharCodes(input.InputValidator.ValidCodes, '0123456789.');
}
else if (validationType == InputValidator.ValidationType.Numeric) {
getCharCodes(input.InputValidator.ValidCodes, '0123456789');
}
input.InputValidator.ValidateChar = function (c) {
return this.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('');
}
function bindEvent(el, eventName, eventHandler) {
if (el.addEventListener) {
el.addEventListener(eventName, eventHandler, false);
} else if (el.attachEvent) {
el.attachEvent('on' + eventName, eventHandler);
}
}
function getCaretPosition(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;
}
}
}
function setCursor(node, pos) {
var node = (typeof (node) === "string" || node instanceof String) ? document.getElementById(node) : node;
if (!node) {
return false;
}
else if (node.createTextRange) {
var textRange = node.createTextRange();
textRange.collapse(true);
textRange.moveEnd(pos);
textRange.moveStart(pos);
textRange.select();
return true;
} else if (node.setSelectionRange) {
node.setSelectionRange(pos, pos);
return true;
}
return false;
}
function validateActive() {
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();
}
return false;
}
});
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();
}
return false;
}
});
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 event
if (/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);
}
else if (/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();
}
return false;
}
else {// Everything else - empty editdiv and allow browser to paste content into it, then cleanup
input.value = '';
waitforpastedata(input, svt);
return true;
}
});
bindEvent(input, 'select', function (e) {
var evt = e || window.event;
if (evt.preventDefault) {
evt.preventDefault();
evt.stopPropagation();
}
return false;
});
bindEvent(input, 'selectstart', function (e) {
var evt = e || window.event;
if (evt.preventDefault) {
evt.preventDefault();
evt.stopPropagation();
}
return false;
});
/* 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 changed
if (input.value !== dt)
triggerEvent('change', input);
}
function waitforpastedata(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 :
new InputValidator(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 :
new InputValidator(document.getElementById('txtValidate'), InputValidator.ValidationType.Custom,'1234abc');
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.
This works for me:
$(document).ready(function () {
$(".onlyNumbersInput").on('keyup keydown blur', function (event) {
$(this).val($(this).val().replace(/[^0-9]/g, ''));
});
});
It's based on #luizfelippe answer, updated for jquery 1.7+
This code allows paste and will remove any non numeric character in realtime.
I think you forgot putting e.preventDefault(); before return.
This is how I do it:
jQuery( '#input').keyup(function() {
var value = jQuery(this).val();
var newValue = value.replace(/\D/g,''); //remove letters
newValue = parseInt(newValue);
jQuery(this).val(newValue);
value = jQuery(this).val();
//just as safety, if some weird character is in the input
if( isNaN (value) || value == "" ){
jQuery(this).val(0);
}
}
The keyup event seems just fine for me to do this, I've also tried keypress and keydown.
My JQuery Solution.
const validKeyCodes = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57]
$('#your_input').on('keypress', function(e) {
return validKeyCodes.indexOf(e.keyCode) > -1
})
text input:
<input id="number" type="text" />
and script:
var number = $('#number');
number.on('input', function () {
$(this).val(getOnlyNumbers($(this).val()));
});
// this function return only numbers as string or ''
function getOnlyNumbers(value) {
let arr = value.toString().split('');
let number = [];
arr.forEach(function (elem) {
let charCode = elem.charCodeAt(0);
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
} else {
number.push(elem);
}
});
return parseInt(number.join('')) || '';
}
KeyCodes or charCodes is not the best way to do this if you use numbers above letters in your laptop and don't have normal keyboard connected. And if you know these numbers above letters, starting with key `(~) , were used to add specific symbols of different nations language. So only numbers will become numbers and letters. For example: key 1(!) - in Lithuanian language is ą .
So better way is to use this var newValue = value.replace(/\D/g,'');
This taken from answer above.
Try this Script:
var str = 5.5;
str = str.toString();
var errnum = [];
var onlyNumbers = [0,1,2,3,4,5,6,7,8,9,"0","1","2","3","4","5","6","7","8","9"];
for(i = 0; i < str.length; i++) {
if(jQuery.inArray(str[i],onlyNumbers) == -1){
errnum.push(str[i]);
}
}
if(errnum.length >= 1){
console.log('not numeric character found!');
}
Related
I been trying to create validation function for input to allow only numeric with two decimal point And max value 99999999.99.
This is what I have tried so far but doesn't seems to be working.
$('#TXTCOST').keypress(function (event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
var input = $(this).val();
if ((input.indexOf('.') != -1) && (input.substring(input.indexOf('.')).length > 2)) {
event.preventDefault();
}
var arr = input.split('.');
if (arr.length == 1 && parseFloat(arr[0]) >= 99999999) {
event.preventDefault();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="TXTCOST"/>
My example below uses a simple regex check for 1-8 digits number with optional 0-2 decimal points:
Edit: Now the code prevents the entry of wrong value. This is done in 2 stages
On key press, make a backup of the current input value then limit user input to allowed keys
Validate current input then revert back to the old value if the new value is invalid.
let allowed_keys = [8, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 190];
let my_regex = /^([0-9]{0,8})(\.{1,1}[0-9]{0,2})?$/;
let old_val;
let x = $('#TXTCOST').on('keydown', function (event) {
let input_value = $(this).val().toString();
old_val = input_value;
let found_dots = input_value.match(/\./g) || [];
let split_input_value = input_value.split('.');
let prevent_default = false;
// console.log('value = ' + $(this).val());
let tests = [];
tests.push(() => {
return allowed_keys.includes(event.which);
});
tests.push(() => {
return (event.which !== 190) || ((event.which === 190) && (input_value.length > 0) && (found_dots.length === 0))
});
tests.forEach(function (test, index) {
if (test() === false) {
event.preventDefault();
}
});
}).on('input', function (event) {
let input_value = $(this).val().toString();
let tests = [];
tests.push(() => {
if (my_regex.test(input_value)) {
return true;
} else {
return false;
}
});
tests.forEach((test, index) => {
if (test() === false) {
$(this).val(old_val)
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="TXTCOST"/>
try like this.
$('#TXTCOST').keypress(function (event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
else{
var input = $(this).val();
if ((input.indexOf('.') != -1) && (input.substring(input.indexOf('.')).length > 2)) {
event.preventDefault();
}
var arr = (input+String.fromCharCode(event.keyCode)).split('.');
if (arr.length == 1 && parseFloat(arr[0]) > 99999999) {
event.preventDefault();
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="TXTCOST"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="TXTCOST"/>
$('#TXTCOST').keypress(function (event) {
if ((event.which != 46 || $this.val().indexOf('.') != -1) &&
((event.which < 48 || event.which > 57) &&
(event.which != 0 && event.which != 8))) {
event.preventDefault();
}
var input = $(this).val();
if ((input.indexOf('.') != -1) && (input.substring(input.indexOf('.')).length > 2)) {
event.preventDefault();
}
var arr = input.split('.');
if (arr.length == 1 && parseFloat(arr[0]) >= 99999999) {
event.preventDefault();
}
});
try this
From another stackoverflow post (How can I add a JavaScript keyboard shortcut to an existing JavaScript Function?) I have this hotkey code:
function doc_keyPress(e) {
if (e.shiftKey && e.keyCode == 80) {
//do something
}
}
document.addEventListener('keyup', doc_keyPress, false);
which works with two keys. But with three keys, shift + l + m for example, it does not work.
the if statement would be:
if (e.shiftKey && e.keyCode == 76 && e.keyCode == 77) {}
again this does not work.
How do I get this working for shift + l + m.
tricky, tricky, but I managed to get it working. Just be aware that browsers have their own hot keys (like chromes [ctrl]+[shift]+i) which may override the function.
<!DOCTYPE html>
<html>
<body>
<input id="myInput" onkeydown="keyDownEvent(event)" onkeyup="resetKeys()">
</body>
</html>
<script>
var key1Pressed=false;
var key2Pressed=false;
function resetKeys(){
key1Pressed=false;
key2Pressed=false;
}
function keyDownEvent(e){
e=e||event, chrCode=(typeof e.which=="number")?e.which:e.keyCode;
if (e.shiftKey && chrCode === 76) key1Pressed=true;
if (e.shiftKey && chrCode === 77) key2Pressed=true;
if(key1Pressed && key2Pressed){
alert('Three Keys Are Pressed');
key1Pressed=false;
key2Pressed=false;
}
}
document.getElementById('myInput').focus();
</script>
Using a closure, I would envisage you can do something like this
var doc_keypress = (function() {
var prevWasL = false;
return function(e) {
if (e.type == 'keypress') {
if (e.shiftKey && !(e.ctrlKey || e.metaKey)) {
if (prevWasL) {
if (e.charCode == 77) {
console.log('doing it');
prevWasL = false;
return;
}
}
if (e.charCode == 76) {
prevWasL = true;
return;
}
}
prevWasL = false;
} else { // keyup
if (e.key == 'Shift') {
prevWasL = false;
}
}
}
}());
document.addEventListener('keypress', doc_keypress);
document.addEventListener('keyup', doc_keypress);
Add both keypress AND keyup event listeners so that the scenario of
Shift + L, release both, Shift + M, doesn't trigger a false positive
This would require shift then L then M being pressed in that order ... if you want either order of L and M, then the code would be a little different, but you should be able to figure that out
NOTE: I use charCode, because firefox at least, keyCode is always 0 on keyPress event
If you're trying to double press or triple press keys and catch an event after this, I've written a simple helper:
function KeyPress(_opts) {
this.opts = Object.assign({}, {
counts: {},
timeouts: {},
timeBetweenPresses: 300
}, _opts || {});
}
KeyPress.prototype.bubbledReset = function bubbledReset(keyCode) {
var self = this;
if (this.opts.timeouts[keyCode]) {
clearTimeout(this.opts.timeouts[keyCode]);
this.opts.timeouts[keyCode] = 0;
}
this.opts.timeouts[keyCode] = setTimeout(function () {
self.opts.counts[keyCode] = 0;
}, this.opts.timeBetweenPresses);
};
KeyPress.prototype.onTap = function onTap(cb) {
var self = this;
return function handler(event) {
self.opts.counts[event.keyCode] = self.opts.counts[event.keyCode] || 0;
self.opts.counts[event.keyCode]++;
self.bubbledReset(event.keyCode);
cb(event.keyCode, self.opts.counts[event.keyCode]);
};
};
Usage
Simply use the onTap method to instance:
var keyPress = new KeyPress();
document.addEventListener('keyup', keyPress.onTap(function (keyCode, count) {
if (keyCode === 68 && count === 3) {
// 68 was tapped 3 times (D key)
}
if (keyCode === 13 && count === 6) {
// 13 was tapped 6 times (ENTER key)
}
}));
Hope this helps someone else!
Or if you prefer es6:
class KeyPress {
constructor(_opts) {
this.opts = Object.assign({}, {
counts: {},
timeouts: {},
timeBetweenPresses: 300
}, _opts || {});
}
bubbledReset(keyCode) {
if (this.timeouts[keyCode]) {
clearTimeout(this.timeouts[keyCode]);
this.timeouts[keyCode] = 0;
}
this.timeouts[keyCode] = setTimeout(() => {
this.counts[keyCode] = 0;
}, this.timeBetweenPresses);
}
onTap(cb) {
return event => {
this.counts[event.keyCode] = this.counts[event.keyCode] || 0;
this.counts[event.keyCode]++;
this.bubbledReset(event.keyCode);
cb(event.keyCode, this.counts[event.keyCode]);
};
}
}
I have a problem. Basically, what happens in my case is that the numbers in my textbox are autoformatted as I type. I don't want this to happen. What I want is that the numbers should be autoformatted only when the user clicks outside the textbox.
In my input tag I have :
onkeyup="format(event, this);"
My javascript function is :
function format(e, obj) {
if (e.keyCode == 36) {
press1(obj);
}
if (e.keyCode == 13) {
return false;
}
if ((e.keyCode <= 34) || (e.keyCode >= 46 && e.keyCode < 58) || (e.keyCode >= 96 && e.keyCode <= 105)) { // //alert(e.keyCode);
obj.value = CommaFormatted(obj.value);
} else {
if (e && e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
} else {
e.cancelBubble = true;
e.returnValue = false;
}
return false;
}
}
where the press1 function is:
function press1(textControlID) {
var text = textControlID;
if (text.getAttribute("maxlength") == text.value.length) {
var FieldRange = text.createTextRange();
FieldRange.moveStart('character', text.value.length);
FieldRange.collapse();
FieldRange.select();
return true;
}
if (text != null && text.value.length > 0) {
if (text.createTextRange) {
var FieldRange = text.createTextRange();
FieldRange.moveStart('character', text.value.length);
FieldRange.collapse();
FieldRange.select();
} else if (text.setSelectionRange) {
var textLength = text.value.length;
text.setSelectionRange(textLength, textLength);
}
}
}
I really hope this could be solved. Please!
You could change onkeyup to onblur, which is the event that gets fired when the control loses focus - clicking out of it.
The onkeyup event fires with every keypress.
I have a condition to allow user to input only 2 decimal points number and restrict the alphabets and other characters. I used the following function:
function isNumberKeyOnlyWithDecimalFormat(event,value,id){
var val = value;
if (event.shiftKey === true) {
event.preventDefault();
}
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 ||
event.keyCode == 190) {
} else {
event.preventDefault();
}
if(val.indexOf('.') !== -1 && event.keyCode == 190){
event.preventDefault();
}
if ((pointPos = $('#'+id).val().indexOf('.')) >= 0){
$('#'+id).attr("maxLength", pointPos+3);
}
else
$('#'+id).removeAttr("maxLength");
}
It is working fine while first time adding. But it restricts the if i want to edit the digits if it has already 2 decimal place. Can anyone help with this?
Try this. It will check the value each time the focus is gone from the input field, but you can use any event you like. It will parse the value as a float, and then round it to 2 decimal points.
Here is the fiddle: http://jsfiddle.net/sAp9D/
HTML:
<input type="text" id="the_id" />
JavaScript:
var input_field = document.getElementById('the_id');
input_field.addEventListener('change', function() {
var v = parseFloat(this.value);
if (isNaN(v)) {
this.value = '';
} else {
this.value = v.toFixed(2);
}
});
Your question is very hard to understand but if you want to check that a string has only 2 decimals then you can just do this
if( value.match(/\./g).length === 2 ) {
// Number has 2 decimals eg. 1.2.3
} else {
// Number is incorrect eg. 1.2.3.4
}
or if you want 1.2 then
if( value.match(/\./g).length === 1 ) {
// Code....
}
I use the following
// This function will only allow digits
function numericFormat( fld , e , extraStrCheck )
{
var sep = 0;
var key = '';
var i = j = 0;
var len = len2 = 0;
var strCheck = '0123456789';
if ( extraStrCheck )
strCheck += extraStrCheck;
var aux = aux2 = '';
var whichCode = (window.Event) ? e.which : e.keyCode;
if (whichCode == 13) return true; // Enter
if (whichCode == 8) return true; // Backspace
if (whichCode == 0) return true; // Null
if (whichCode == 9) return true; // Tab
key = String.fromCharCode(whichCode); // Get key value from key code
if ( strCheck.indexOf(key) == -1 ) return false; // Not a valid key
var x = new String(fld.value);
if ( key == '.' )
{
var exp = /\./;
var a = x.search(exp);
if ( a != -1 ) return false;
}
}
// samer code on change or on blur event
function allow2decimal(obj){
var v = parseFloat($(obj).val());
if (isNaN(v)) {
$(obj).value = '';
} else {
newVal = v.toFixed(2);
if(newVal >= 100){
$(obj).val( 100 );
}else{
$(obj).val(newVal);
}
}
}
//usage
<input
onkeypress="return numericFormat( this , event , '.');"
onchange="allow2decimal(this)"
value="0.1"
id="factory_silk" name="factory_silk" />
<html>
<head>
<script type="text/javascript">
function NumAndTwoDecimals(e, field) {
var val = field.value;
var re = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)$/g;
var re1 = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)/g;
if (re.test(val)) {
}
else {
val = re1.exec(val);
if (val) {
field.value = val[0];
}
else {
field.value = "";
}
}
}
</script>
</head>
<body>
<input type="text" name="text" onkeyup="NumAndTwoDecimals(event , this);">
</body>
</html>
$('.number').keypress(function(evt){
var str = $(this).val();
var index = str.indexOf('.');
if(index==-1){index=0;}else{index= index+1;}
var extrapoint = str.indexOf('.',index);
if(extrapoint>0){$(this).val(str.slice(0,-1));}
var charCode = (evt.which) ? evt.which : event.keyCode;
if(charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
var validNumber = new RegExp(/^\d*\.?\d*$/);
var lastValid = $(this).val();
if (validNumber.test($(this).val()))
{
lastValid = $(this).val();
}
else
{
$(this).val(lastValid);
}
});
Following on from another question I asked, i really didnt seem to be getting anywhere. Due to my ineptitude. I chose the guys answer because , well he answered my question.
I am gathering I didnt ask the right question cos I have no idea what to do ..
So issue is I have input element . Keeping it simple;
<input type="text" maxlength="12" name="price" id="price" class="foo">
I want users to be able to type in numbers only and only one period ( . ) anywhere in that price. so could be 3.00 or 300.00 or 3000
Could someone please help me out, I am going goggle eyed.
The Older question asked was here Quick regex with alert
You could, in the change event of the input, check if the number format is OK. This code will try to get the number and remove anything else: (I'm assuming you use jQuery, if not, please do)
$('#price').change(function() {
$(this).val($(this).val().match(/\d*\.?\d+/));
});
See it working here.
EDIT: if you don't have jQuery, this code does the same (at least in Chrome):
document.getElementById('price').onchange = function() {
this.value = this.value.match(/\d*\.?\d+/);
};
EDIT 2: not sure if I follow, but you could add this too to prevent letters and other characters before the change event:
$('#price').keypress(function(event) {
var code = (event.keyCode ? event.keyCode : event.which);
if (!(
(code >= 48 && code <= 57) //numbers
|| (code == 46) //period
)
|| (code == 46 && $(this).val().indexOf('.') != -1)
)
event.preventDefault();
});
Here is my solution(It also validates data/values copy&pasted):
function InputValidator(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)
return true;
}
else {
if (this[i][target] === value)
return true;
}
}
return false;
};
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 in this) {
if (this[a] === value)
return true;
}
return false;
};
function getCharCodes(arrTarget, chars) {
for (var i = 0; i < chars.length; i++) {
arrTarget.Add(chars[i].charCodeAt(0));
}
}
function triggerEvent(name, element) {
if (document.createEventObject) {
// dispatch for IE
var evt = document.createEventObject();
return element.fireEvent('on' + name, evt)
}
else {
// dispatch for firefox + others
var evt = document.createEvent("HTMLEvents");
evt.initEvent(name, true, true); // event type,bubbling,cancelable
return !element.dispatchEvent(evt);
}
}
if (validationType == InputValidator.ValidationType.Custom) {
if (typeof (validChars) === 'undefined')
throw 'Please add valid characters';
getCharCodes(input.InputValidator.ValidCodes, validChars);
}
else if (validationType == InputValidator.ValidationType.Decimal) {
getCharCodes(input.InputValidator.ValidCodes, '0123456789.');
}
else if (validationType == InputValidator.ValidationType.Numeric) {
getCharCodes(input.InputValidator.ValidCodes, '0123456789');
}
input.InputValidator.ValidateChar = function (c) {
return this.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('');
}
function bindEvent(el, eventName, eventHandler) {
if (el.addEventListener) {
el.addEventListener(eventName, eventHandler, false);
} else if (el.attachEvent) {
el.attachEvent('on' + eventName, eventHandler);
}
}
function getCaretPosition(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;
}
}
}
function setCursor(node, pos) {
var node = (typeof (node) === "string" || node instanceof String) ? document.getElementById(node) : node;
if (!node) {
return false;
}
else if (node.createTextRange) {
var textRange = node.createTextRange();
textRange.collapse(true);
textRange.moveEnd(pos);
textRange.moveStart(pos);
textRange.select();
return true;
} else if (node.setSelectionRange) {
node.setSelectionRange(pos, pos);
return true;
}
return false;
}
function validateActive() {
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();
}
return false;
}
});
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();
}
return false;
}
});
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 event
if (/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);
}
else if (/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();
}
return false;
}
else {// Everything else - empty editdiv and allow browser to paste content into it, then cleanup
input.value = '';
waitforpastedata(input, svt);
return true;
}
});
bindEvent(input, 'select', function (e) {
var evt = e || window.event;
if (evt.preventDefault) {
evt.preventDefault();
evt.stopPropagation();
}
return false;
});
bindEvent(input, 'selectstart', function (e) {
var evt = e || window.event;
if (evt.preventDefault) {
evt.preventDefault();
evt.stopPropagation();
}
return false;
});
/* 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 changed
if (input.value !== dt)
triggerEvent('change', input);
}
function waitforpastedata(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 :
new InputValidator(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 :
new InputValidator(document.getElementById('txtValidate'), InputValidator.ValidationType.Custom,'1234abc');
Cambraca aproach kind of works, but the best one is the last mentioned approach , you cancel the keypress event filtering the keys before it shows up instead of undoing what was already done. A consequence of changing the value after the fact is that it may affect the position of the caret in the field.
Here's an example of abstracting the idea in a cross-browser way. Somebody should port this to a jQuery plugin http://www.qodo.co.uk/assets/files/javascript-restrict-keyboard-character-input.html
Ok, I guess I'll port it. But I'm not a jQuery guy so this is an untested bare bones jQuery plugin that uses their code
http://jsfiddle.net/mendesjuan/VNSU7/3
(function( $ ) {
$.fn.restrict = function(regExp, additionalRestriction) {
function restrictCharacters(myfield, e, restrictionType) {
var code = e.which;
var character = String.fromCharCode(code);
// if they pressed esc... remove focus from field...
if (code==27) { this.blur(); return false; }
// ignore if they are press other keys
// strange because code: 39 is the down key AND ' key...
// and DEL also equals .
if (!e.originalEvent.ctrlKey && code!=9 && code!=8 && code!=36 && code!=37 && code!=38 && (code!=39 || (code==39 && character=="'")) && code!=40) {
if (character.match(restrictionType)) {
return additionalRestriction(myfield.value, character);
} else {
return false;
}
}
}
this.keypress(function(e){
if (!restrictCharacters(this, e, regExp)) {
e.preventDefault();
}
});
};
})( jQuery );
$('#field').restrict(/[0-9\.]/g, function (currentValue, newChar) {
return !(currentValue.indexOf('.') != -1 && newChar == ".");
});