Limit input to numbers and . on input field - javascript

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 == ".");
});

Related

Create a javascript object

I would say I am fairly decent with javascript and jQuery, well, enough to get the job done and done pretty well.
I do however lack a deep understanding of js.
I have created some functions for highlighting table elements.
ctrl+click toggles selections
shift+click+drag highlights selection
My question does not pertain to whether or not my implementation is the best way or not but ...
How do I abstract this functionality so I can add this functionality to any table. Like if I add more highlighting features and such and put this in its own .js file. How would I attach it to any html table?
Sorry if this has already been answered, but I could not think of what to search for.
Thank you.
****Newest Code****
This code is in its own .js file and is attached to my table.
All the current functionality is there. The only thing I am weary of is the .off() functions. In my case, I am reloading new tables.... as I type this, I realize I should just empty the tr's from the table instead of recreating a new table all the time, then I could get rid of the .off() calls.
$.fn.addEvents = function(obj)
{
console.log("Adding events to table");
var properties = $.extend(true,
{
shifting: false,
ctrling: false,
mousing: false,
mouseenter: 0,
mouseleave: 0,
mousestartindex: 0,
mouseenterindex: 0,
mouseleaveindex: 0,
trajectory: null,
tmptrajectory: null
}, obj || {});
$(document)
.off('mouseup')
.on('mouseup', function(e)
{
properties.mousing = false;
properties.trajectory = null;
})
.off("keyup")
.on("keyup", function(e)
{
if(e.which == 16)
{
properties.shifting = false;
}
if(e.which == 17)
{
properties.ctrling = false;
}
})
.off("keydown")
.on("keydown", function(e)
{
if(e.which == 16)
{
properties.shifting = true;
}
if(e.which == 17)
{
properties.ctrling = true;
}
if($(this).find('tr.selected').length > 0)
{
switch(e.which)
{
//case 37: // left
//break;
case 38: // up
var index = $(this).find('tr.selected').index();
if(index > 0)
{
$(this).find('tr').removeClass('selected');
$(this).find('tr td').removeClass('selected');
$(this).find('tr:eq(' + index + ')').addClass('selected');
$(this).find('tr:eq(' + index + ') td').addClass('selected');
}
break;
//case 39: // right
//break;
case 40: // down
var index = $(this).find('tr.selected').index();
if(index < $(this).find('tr').length - 2)
{
$(this).find('tr').removeClass('selected');
$(this).find('tr td').removeClass('selected');
$(this).find('tr:eq(' + (index+2) + ')').addClass('selected');
$(this).find('tr:eq(' + (index+2) + ') td').addClass('selected');
}
break;
case 117: // f6
var index = $(this).find('tr.selected').index();
if(index > 0)
{
....
}
break;
case 118: // f7
var index = $(this).find('tr.selected').index();
if(index < $(this).find('tr').length - 1)
{
....
}
break;
default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
}
return;
});
return $(this)
.off('click')
.off('contextmenu')
.on('click', function()
{
if(!properties.ctrling && !properties.shifting)
{
$('#datatablebody tr, #datatablebody tr td').removeClass('selected');
$(this).addClass('selected');
$(this).find('td').addClass('selected');
}
else if(properties.ctrling && $(this).hasClass('selected'))
{
$(this).removeClass('selected');
$(this).find('td').removeClass('selected');
}
else if(properties.ctrling && !$(this).hasClass('selected'))
{
$(this).addClass('selected');
$(this).find('td').addClass('selected');
}
})
.on('contextmenu', function(ev)
{
ev.preventDefault();
$('#datatablebody tr, #datatablebody tr td').removeClass('selected');
$(this).addClass('selected');
$(this).find('td').addClass('selected');
showContextMenuTR($(this).closest('tr').attr('id'), ev.clientX, ev.clientY);
return false;
})
.off('mousedown')
.on('mousedown', function(e)
{
properties.mousing = true;
properties.mousestartindex = $(this).index();
if(properties.shifting && properties.mousing)
{
multiselectrow($(this));
}
})
.off('mouseenter')
.on('mouseenter', function(e)
{
properties.mouseenter = e.clientY;
properties.mouseenterindex = $(this).index();
if(properties.tmptrajectory === properties.trajectory)
{
if(properties.shifting && properties.mousing)
{
multiselectrow($(this));
}
}
})
.off('mouseleave')
.on('mouseleave', function(e)
{
properties.mouseleave = e.clientY;
if(properties.shifting && properties.mousing)
{
properties.tmptrajectory = properties.mouseenter - properties.mouseleave < 0?1:-1;
}
if(properties.trajectory != null && properties.tmptrajectory !== properties.trajectory && $(this).index() !== properties.mousestartindex)
{
if(properties.shifting && properties.mousing)
{
multiselectrow($(this));
}
}
if(properties.shifting && properties.mousing)
{
if(properties.trajectory == null)
{
properties.trajectory = properties.tmptrajectory;
}
else if(properties.tmptrajectory !== properties.trajectory && $(this).index() === properties.mousestartindex)
{
properties.trajectory = properties.tmptrajectory;
}
}
})
.off('mouseup')
.on('mouseup', function(e)
{
properties.mousing = false;
properties.trajectory = null;
if(properties.shifting && properties.mousing)
{
multiselectrow($(this));
}
});
}
function multiselectrow(obj)
{
if($(obj).hasClass('selected'))
{
$(obj).removeClass('selected');
$(obj).find('td').removeClass('selected');
}
else
{
$(obj).addClass('selected');
$(obj).find('td').addClass('selected');
}
}
you can wrap all this in a function since you have some local variables related to individual selection
$.fn.addEvents = function(obj) {
var properties = $.extend(true, {
shifting: false,
ctrling: false,
mousing: false,
mouseenter: 0,
mouseleave: 0,
trajectory: null
}, obj || {});
return $(this)
.off('click')
.off('contextmenu')
.on('click', function() {
.....
})
.on('mouseleave', function(e) {
//rename your local variables with `properties.` prefix
properties.mouseleave = e.clientY;
if (properties.shifting && properties.mousing) {
tmptrajectory = properties.mouseenter - properties.mouseleave < 0 ? 1 : -1;
}
if ($(this).hasClass('selected') && properties.shifting && properties.mousing && properties.trajectory != null && properties.trajectory != tmptrajectory) {
$(this).removeClass('selected');
$(this).find('td').removeClass('selected');
}
....
});
}
usage
$('#datatablebody tr').addEvents({ shifting: false, ctrling: true }); //custom settings
$('#someother tr').addEvents(); //default settings
you could add that functionality to a class and add that class to the tables you want to affect...
Here I create the class .myTableBeh and all tables with that class will have the behaviour you programmed.
var shifting = false;
var ctrling = false;
var mousing = false;
var mouseenter = 0;
var mouseleave = 0;
var trajectory = null;
$('.myTableBeh tr')
.off('click')
.off('contextmenu')
.on('click', function()
{
if(!ctrling)
{
$('.myTableBeh tr, .myTableBeh tr td').removeClass('selected');
$(this).addClass('selected');
$(this).find('td').addClass('selected');
}
else if(ctrling && $(this).hasClass('selected'))
{
$(this).removeClass('selected');
$(this).find('td').removeClass('selected');
}
else if(ctrling && !$(this).hasClass('selected'))
{
$(this).addClass('selected');
$(this).find('td').addClass('selected');
}
})
.on('contextmenu', function(ev)
{
ev.preventDefault();
$('.myTableBeh tr, .myTableBeh tr td').removeClass('selected');
$(this).addClass('selected');
$(this).find('td').addClass('selected');
showContextMenuTR($(this).closest('tr').attr('id'), ev.clientX, ev.clientY);
return false;
})
.off('mousedown')
.on('mousedown', function(e)
{
mousing = true;
multiselectrow($(this));
})
.off('mouseenter')
.on('mouseenter', function(e)
{
mouseenter = e.clientY;
multiselectrow($(this));
})
.off('mouseleave')
.on('mouseleave', function(e)
{
mouseleave = e.clientY;
if(shifting && mousing)
{
tmptrajectory = mouseenter - mouseleave < 0?1:-1;
}
if($(this).hasClass('selected') && shifting && mousing && trajectory != null && trajectory != tmptrajectory)
{
$(this).removeClass('selected');
$(this).find('td').removeClass('selected');
}
if(shifting && mousing && trajectory == null)
{
trajectory = tmptrajectory;
}
})
.off('mouseup')
.on('mouseup', function(e)
{
mousing = false;
trajectory = null;
multiselectrow($(this));
});
Thanks to the answer from #JAG I was able to create a nice add on to any HTML table that handles highlighting.
Check out the fiddle for the working version and please use it if you find it helpful or useful for your site.
You can even implement keys to move the tr position up or down in the table. I removed my implementation because it was specific to the project I am working on.
I made it so you have to mouse over the table in order to interact with it and mouse leave to un-focus it.
https://jsfiddle.net/kwj74kg0/2/
//Add the events simply by running this
$('#dtable tr').addEvents(0);
/**
* This add on can be applied and customized to any html tr set i.e. $('#tableid tr').addEvents()
* It will add highlighting capability to the table.
*
* Single click highlight tr
* Click -> Shift + click highlight/toggle range
* Shift+MouseDown+Drag highlight/toggle range
* Ctrl+Click toggle item
*
*
* #author Michaela Ervin
*
* #param tabindex
*
* Help from JAG on http://stackoverflow.com/questions/39022116/create-a-javascript-object
*/
$.fn.addEvents = function(tabindex)
{
console.log("Adding events to table");
var properties = $.extend(true,
{
shifting: false,
ctrling: false,
mousing: false,
mouseenter: 0,
mouseleave: 0,
mousestartindex: 0,
mouseenterindex: null,
mouseleaveindex: null,
trajectory: null,
tmptrajectory: null
}, {});
/**
* Add events to closest table.
*/
$(this)
.closest('table')
.attr('tabindex', tabindex)
.off('mouseenter')
.on('mouseenter', function()
{
$(this).focus();
})
.off('mouseleave')
.on('mouseleave', function()
{
$(this).blur();
properties.mousing = false;
properties.trajectory = null;
properties.mouseenterindex = null;
properties.mouseleaveindex = null;
properties.mouseintermediateindex = null;
})
.off("keyup")
.on("keyup", function(e)
{
if(e.which == 16)
{
properties.shifting = false;
}
if(e.which == 17)
{
properties.ctrling = false;
}
})
.off("keydown")
.on("keydown", function(e)
{
if(e.which == 16)
{
properties.shifting = true;
}
if(e.which == 17)
{
properties.ctrling = true;
}
if($(this).find('tr.selected').length > 0)
{
switch(e.which)
{
//case 37: // left
//break;
case 38: // up
var index = $(this).find('tr.selected').index();
if(index > 0)
{
$(this).find('tr').removeClass('selected');
$(this).find('tr td').removeClass('selected');
$(this).find('tr:eq(' + index + ')').addClass('selected');
$(this).find('tr:eq(' + index + ') td').addClass('selected');
}
break;
//case 39: // right
//break;
case 40: // down
var index = $(this).find('tr.selected').index();
if(index < $(this).find('tr').length - 2)
{
$(this).find('tr').removeClass('selected');
$(this).find('tr td').removeClass('selected');
$(this).find('tr:eq(' + (index+2) + ')').addClass('selected');
$(this).find('tr:eq(' + (index+2) + ') td').addClass('selected');
}
break;
case 117: // f6
var index = $(this).find('tr.selected').index();
if(index > 0)
{
//Function to move tr 'up'.
}
break;
case 118: // f7
var index = $(this).find('tr.selected').index();
if(index < $(this).find('tr').length - 1)
{
//Function to move tr 'down'.
}
break;
default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
}
return;
});
/**
* Add tr specific events
*/
return $(this)
.off('click')
.on('click', function()
{
if(!properties.shifting && properties.mouseenterindex != null)
{
properties.mouseenterindex = null;
properties.mousing = false;
}
if(!properties.ctrling && !properties.shifting && properties.mouseenterindex == null)
{
$(this).parent().find('tr').removeClass('selected');
$(this).parent().find('tr td').removeClass('selected');
$(this).addClass('selected');
$(this).find('td').addClass('selected');
}
else if(properties.ctrling && $(this).hasClass('selected'))
{
$(this).removeClass('selected');
$(this).find('td').removeClass('selected');
}
else if(properties.ctrling && !$(this).hasClass('selected'))
{
$(this).addClass('selected');
$(this).find('td').addClass('selected');
}
if(properties.mouseenterindex == null)
{
properties.mouseenterindex = $(this).index();
}
else if(properties.shifting && properties.mouseenterindex != null)
{
properties.mouseleaveindex = $(this).index();
highlightRange($(this).parent(), properties.mouseenterindex, properties.mouseleaveindex, properties.mouseenterindex);
properties.mouseenterindex = null;
properties.mouseleaveindex = null;
}
})
.off('contextmenu')
.on('contextmenu', function(ev)
{
ev.preventDefault();
$(this).parent().find('tr').removeClass('selected');
$(this).parent().find('tr td').removeClass('selected');
$(this).addClass('selected');
$(this).find('td').addClass('selected');
//Put your context menu here
return false;
})
.off('mousedown')
.on('mousedown', function(e)
{
properties.mousing = true;
properties.mousestartindex = $(this).index();
if(properties.shifting && properties.mousing && properties.mouseenterindex == null)
{
multiselectrow($(this));
}
})
.off('mouseenter')
.on('mouseenter', function(e)
{
properties.mouseenter = e.clientY;
if(properties.tmptrajectory === properties.trajectory)
{
if(properties.shifting && properties.mousing)
{
multiselectrow($(this));
}
}
})
.off('mouseleave')
.on('mouseleave', function(e)
{
properties.mouseleave = e.clientY;
if(properties.shifting && properties.mousing)
{
properties.tmptrajectory = properties.mouseenter - properties.mouseleave < 0?1:-1;
}
if(properties.trajectory != null && properties.tmptrajectory !== properties.trajectory && $(this).index() !== properties.mousestartindex)
{
if(properties.shifting && properties.mousing)
{
multiselectrow($(this));
}
}
if(properties.shifting && properties.mousing)
{
if(properties.trajectory == null)
{
properties.trajectory = properties.tmptrajectory;
}
else if(properties.tmptrajectory !== properties.trajectory && $(this).index() === properties.mousestartindex)
{
properties.trajectory = properties.tmptrajectory;
}
}
})
.off('mouseup')
.on('mouseup', function(e)
{
properties.mousing = false;
properties.trajectory = null;
if(!properties.shifting)
{
properties.mouseenterindex = null;
properties.mouseleaveindex = null;
}
});
}
function multiselectrow(obj)
{
if($(obj).hasClass('selected'))
{
$(obj).removeClass('selected');
$(obj).find('td').removeClass('selected');
}
else
{
$(obj).addClass('selected');
$(obj).find('td').addClass('selected');
}
}
function highlightRange(obj, start, end, mouseenterindex)
{
if(start < end)
{
for(var i=start; i<=end; i+=1)
{
if(i !== mouseenterindex)
{
multiselectrow($(obj).find('tr').eq(i));
}
}
}
else
{
for(var i=start; i>=end; i-=1)
{
if(i !== mouseenterindex)
{
multiselectrow($(obj).find('tr').eq(i));
}
}
}
}

three button keyCode hotkey javascript

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 cant hide jquery autocomplete with my functions

I am creating project which it searches musics dynamicly with JSON.
Here is my html:
<div id="custom-search-input">
<div class="input-group col-md-12">
<input type="text" class="form-control input-lg" placeholder="Search query..." id="searchquery" autocomplete="off" />
<span class="input-group-btn">
<button class="btn btn-info btn-lg" type="button" id="searchbuttonheader" onclick="search();">
<i class="glyphicon glyphicon-search"></i>
</button>
</span>
</div>
</div>
My search function called search(); ... Before I integrated jquery autocomplete I made when I click ENTER on keyboard in searchquery input it executes search(); function. To do this here is my JS code:
// ENTER KEY SEARCH //
$.fn.enterKey = function (fnc) {return this.each(function () {$(this).keypress(function (ev) {
var keycode = (ev.keyCode ? ev.keyCode : ev.which);
if (keycode == '13') {search();}})})
}
$("#searchquery").enterKey(function () {search();});
// ENTER KEY SEARCH //
OKAY ITS WORKING... BUT...
After integration the jquery autocomplete when I type something in searchquery input it gives some autocomplete data. Here is JS:
$('#searchquery').autoComplete({
minChars: 1,
delay: 500,
source: function(term, response){
$.getJSON('<?php echo $url_autocomplete; ?>', { query: term }, function(data){ response(data); });
},
onSelect: function(e, term, item){
search();
//alert('Item selected by '+(e.type == 'keydown' ? 'pressing enter' : 'mouse click')+'.');
}
});
When I click one of them the autocomplete hides and searches the text. But when I don't select any of them and hit enter it searches but the autocomplete is not hiding.
I WANT:
When I type something in searchquery input then I hit enter hide autocomplete suggestions and make search();.
You are not using jquery-ui-autocomplete but you use jQuery-autoComplete from Pixabay am I right? Ok, after see the code, there's no close method provided, so i add one to the original source code. You can copy and use below's jquery.auto-complete.js and call $("#searchquery").autoComplete('close'); to close the suggestion. See below example how to use it :
$("#searchquery").enterKey(function (e) {
$("#searchquery").autoComplete('close');
// .. DO YOUR SEARCH HERE ..
});
Use below's modified jquery.auto-complete.js.
/*
jQuery autoComplete v1.0.7
Copyright (c) 2014 Simon Steinberger / Pixabay
GitHub: https://github.com/Pixabay/jQuery-autoComplete
License: http://www.opensource.org/licenses/mit-license.php
*/
(function($){
$.fn.autoComplete = function(options){
var o = $.extend({}, $.fn.autoComplete.defaults, options);
// public methods
if (typeof options == 'string') {
this.each(function(){
var that = $(this);
if (options == 'destroy') {
$(window).off('resize.autocomplete', that.updateSC);
that.off('blur.autocomplete focus.autocomplete keydown.autocomplete keyup.autocomplete');
if (that.data('autocomplete'))
that.attr('autocomplete', that.data('autocomplete'));
else
that.removeAttr('autocomplete');
$(that.data('sc')).remove();
that.removeData('sc').removeData('autocomplete');
} else if (options == 'close') {
// Add new method to close the suggestion box
$(that.data('sc')).hide();
}
});
return this;
}
return this.each(function(){
var that = $(this);
// sc = 'suggestions container'
that.sc = $('<div class="autocomplete-suggestions '+o.menuClass+'"></div>');
that.data('sc', that.sc).data('autocomplete', that.attr('autocomplete'));
that.attr('autocomplete', 'off');
that.cache = {};
that.last_val = '';
that.updateSC = function(resize, next){
that.sc.css({
top: that.offset().top + that.outerHeight(),
left: that.offset().left,
width: that.outerWidth()
});
if (!resize) {
that.sc.show();
if (!that.sc.maxHeight) that.sc.maxHeight = parseInt(that.sc.css('max-height'));
if (!that.sc.suggestionHeight) that.sc.suggestionHeight = $('.autocomplete-suggestion', that.sc).first().outerHeight();
if (that.sc.suggestionHeight)
if (!next) that.sc.scrollTop(0);
else {
var scrTop = that.sc.scrollTop(), selTop = next.offset().top - that.sc.offset().top;
if (selTop + that.sc.suggestionHeight - that.sc.maxHeight > 0)
that.sc.scrollTop(selTop + that.sc.suggestionHeight + scrTop - that.sc.maxHeight);
else if (selTop < 0)
that.sc.scrollTop(selTop + scrTop);
}
}
}
$(window).on('resize.autocomplete', that.updateSC);
that.sc.appendTo('body');
that.sc.on('mouseleave', '.autocomplete-suggestion', function (){
$('.autocomplete-suggestion.selected').removeClass('selected');
});
that.sc.on('mouseenter', '.autocomplete-suggestion', function (){
$('.autocomplete-suggestion.selected').removeClass('selected');
$(this).addClass('selected');
});
that.sc.on('mousedown', '.autocomplete-suggestion', function (e){
var item = $(this), v = item.data('val');
if (v || item.hasClass('autocomplete-suggestion')) { // else outside click
that.val(v);
o.onSelect(e, v, item);
that.sc.hide();
}
return false;
});
that.on('blur.autocomplete', function(){
try { over_sb = $('.autocomplete-suggestions:hover').length; } catch(e){ over_sb = 0; } // IE7 fix :hover
if (!over_sb) {
that.last_val = that.val();
that.sc.hide();
setTimeout(function(){ that.sc.hide(); }, 350); // hide suggestions on fast input
} else if (!that.is(':focus')) setTimeout(function(){ that.focus(); }, 20);
});
if (!o.minChars) that.on('focus.autocomplete', function(){ that.last_val = '\n'; that.trigger('keyup.autocomplete'); });
function suggest(data){
var val = that.val();
that.cache[val] = data;
if (data.length && val.length >= o.minChars) {
var s = '';
for (var i=0;i<data.length;i++) s += o.renderItem(data[i], val);
that.sc.html(s);
that.updateSC(0);
}
else
that.sc.hide();
}
that.on('keydown.autocomplete', function(e){
// down (40), up (38)
if ((e.which == 40 || e.which == 38) && that.sc.html()) {
var next, sel = $('.autocomplete-suggestion.selected', that.sc);
if (!sel.length) {
next = (e.which == 40) ? $('.autocomplete-suggestion', that.sc).first() : $('.autocomplete-suggestion', that.sc).last();
that.val(next.addClass('selected').data('val'));
} else {
next = (e.which == 40) ? sel.next('.autocomplete-suggestion') : sel.prev('.autocomplete-suggestion');
if (next.length) { sel.removeClass('selected'); that.val(next.addClass('selected').data('val')); }
else { sel.removeClass('selected'); that.val(that.last_val); next = 0; }
}
that.updateSC(0, next);
return false;
}
// esc
else if (e.which == 27) that.val(that.last_val).sc.hide();
// enter or tab
else if (e.which == 13 || e.which == 9) {
var sel = $('.autocomplete-suggestion.selected', that.sc);
if (sel.length && that.sc.is(':visible')) { o.onSelect(e, sel.data('val'), sel); setTimeout(function(){ that.sc.hide(); }, 20); }
}
});
that.on('keyup.autocomplete', function(e){
if (!~$.inArray(e.which, [13, 27, 35, 36, 37, 38, 39, 40])) {
var val = that.val();
if (val.length >= o.minChars) {
if (val != that.last_val) {
that.last_val = val;
clearTimeout(that.timer);
if (o.cache) {
if (val in that.cache) { suggest(that.cache[val]); return; }
// no requests if previous suggestions were empty
for (var i=1; i<val.length-o.minChars; i++) {
var part = val.slice(0, val.length-i);
if (part in that.cache && !that.cache[part].length) { suggest([]); return; }
}
}
that.timer = setTimeout(function(){ o.source(val, suggest) }, o.delay);
}
} else {
that.last_val = val;
that.sc.hide();
}
}
});
});
}
$.fn.autoComplete.defaults = {
source: 0,
minChars: 3,
delay: 150,
cache: 1,
menuClass: '',
renderItem: function (item, search){
// escape special characters
search = search.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
var re = new RegExp("(" + search.split(' ').join('|') + ")", "gi");
return '<div class="autocomplete-suggestion" data-val="' + item + '">' + item.replace(re, "<b>$1</b>") + '</div>';
},
onSelect: function(e, term, item){}
};
}(jQuery));

Unable To get Selected text on Enter key press from list box

I am trying for smart search on my web page, so in my search on Click event I am getting Text which is selected in same textarea and but when I try with On keypress I'm unable to do find text of selected item. I am using jquery1.4.2 and tried option:select but still fail to do so...
My Code for click
$(document).ready(function() {
$('#ctl00_ContentPlaceHolder1_smartSearch').keyup(function(e) {
var str = document.getElementById('ctl00_ContentPlaceHolder1_smartSearch');
//alert("hi");
if (str.value.length >= 2) {
if (e.keyCode != 40 && e.keyCode != 38 && e.keyCode != 13) {
var str1 = str.value;
var str2 = str1.replace(' ', '+')
var url = "../SiteCache/90D/SmartGetQuoteData.aspx?Type=EQ&text=" + str2;
$("#ajax_response_smart").load(url);
}
$("#ajax_response_smart").show();
$('#listEQ li').live('click', function() {
var selected = $(this).text();
$("#ajax_response_smart").remove();
if (selected != "") {
var scripcode = selected.split("|");
document.getElementById('ctl00_ContentPlaceHolder1_smartSearch').value = scripcode[0];
document.getElementById('ctl00_ContentPlaceHolder1_hdnCode').value = scripcode[2];
}
});
var $listItems = $('#listEQ li');
var key = e.keyCode,
$selected = $listItems.filter('.ui-state-hover'),
$current;
if (key != 40 && key != 38 && key != 13)
{ return; }
else {
$listItems.removeClass('ui-state-hover');
}
if (key == 40) // Down key
{
if (!$selected.length || $selected.is(':last-child')) {
$current = $listItems.eq(0);
}
else {
$current = $selected.next();
}
}
else if (key == 38) // Up key
{
if (!$selected.length || $selected.is(':first-child')) {
$current = $listItems.last();
}
else {
$current = $selected.prev();
}
}
else if (key == 13) {
}
}
else {
$("#ajax_response_smart").hide();
}
if (typeof $current != "undefined") {
$current.addClass('ui-state-hover');
}
});
$("#ajax_response_smart").mouseover(function() {
var $listItems1 = $('#listEQ li');
$selected1 = $listItems1.filter('.ui-state-hover');
$(this).find("#listEQ li").mouseover(function() {
($selected1).removeClass("ui-state-hover");
$(this).addClass("ui-state-hover");
});
$(this).find("#listEQ li").mouseout(function() {
$(this).removeClass("ui-state-hover");
});
});
});
Please Suggest and Thanks in advance
hey i got my the answer i called the keypress event on my textbox in aspx page and from there i came on the currently paosted js page then on keypress event i got value.i.e not able to use keyup event to detect enter

input field, only numbers jquery/js

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!');
}

Categories