How to allow only defined characters as input using jQuery? - javascript

How do i allow special characters such as hyphen,comma,slash,space key,backspace key,delete key along with alphanumeric values and restrict the rest in jQuery?
As this criteria(allowed characters/input values) varies from field to field, i would like to make it as a utility method which accepts input field id and allowed characters as parameters.
for example: limitCharacters(textid, pattern)

​You can just check the keyCode on keydown and run preventDefault() if match:
$('input').keydown(function(e) {
if (e.which == 8) { // 8 is backspace
e.preventDefault();
}
});​
http://jsfiddle.net/GVb6L/
If you need to restrict to certain chars AND keyCodes + make it into a jQuery plugin, try something like:
$.fn.restrict = function( chars ) {
return this.keydown(function(e) {
var found = false, i = -1;
while(chars[++i] && !found) {
found = chars[i] == String.fromCharCode(e.which).toLowerCase() ||
chars[i] == e.which;
}
found || e.preventDefault();
});
};
$('input').restrict(['a',8,'b']);​
http://jsfiddle.net/DHCUg/

I did something like this but in jQuery plugin format. This example will only allow numbers and full stops.
You can call this by writing:
$("input").forceNumeric();
And the plugin:
jQuery.fn.forceNumeric = function () {
return this.each(function () {
$(this).keydown(function (e) {
var key = e.which || e.keyCode;
if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
// numbers
key >= 48 && key <= 57 ||
// Numeric keypad
key >= 96 && key <= 105 ||
// comma, period and minus, . on keypad
key == 190 || key == 188 || key == 109 || key == 110 ||
// Backspace and Tab and Enter
key == 8 || key == 9 || key == 13 ||
// Home and End
key == 35 || key == 36 ||
// left and right arrows
key == 37 || key == 39 ||
// Del and Ins
key == 46 || key == 45)
return true;
return false;
});
});
}

I would suggest using David solution for modifier keys like backspace and delete and this code below for characters:
var chars = /[,\/\w]/i; // all valid characters
$('input').keyup(function(e) {
var value = this.value;
var char = value[value.length-1];
if (!chars.test(char)) {
$(this).val(value.substring(0, value.length-1));
}
});
Also, I've experienced some problems with keydown so I'd do it on keyup.
Demo: http://jsfiddle.net/elclanrs/QjVGV/ (try typing a dot . or semicolon ;)

Related

How to restrict apart from alphabets and numbers any other keys (function keys, shortcut keys etc.) press action on datatable search input?

Jquery:
Is there please an option to start the search only alphabet and number keys have been typed in?
Datatable globally searching should initiate at least with 3 characters
$(document).on('draw.dt','.dataTable', function() {
$(".dataTables_filter input").off().on("input keyup", function(e) {
// if value length is greater than 3 or user press enter (keycode = 13) on search we will search on datatable
if(this.value.length >= 3 || e.keyCode == 13 || this.value == "") {
var dataTable = $('.table').DataTable();
dataTable.search(this.value).draw();
}
});
});
Solution:
Check this solution. I hope, it will work.
$(document).on('draw.dt','.dataTable', function() {
$(".dataTables_filter input").off().on("input keyup", function(e) {
// if value length is greater than 3 or user presses enter (keycode = 13) on search
// we will search on datatable
if(this.value.length >= 3 || e.keyCode == 13 || this.value == "") {
var checkBackspaceEnter = e.keyCode == 8 || e.keyCode == 13;
// if user removes a character from search we will search
var checkAlphabet = (e.keyCode >= 58 && e.keyCode <= 90);
// check on alphabets
var checkNum = (e.keyCode >= 48 && e.keyCode <= 57
|| e.keyCode >= 96 && e.keyCode <= 105);
// check on number values
var ctrlCombine = (e.keyCode == 17 || ((e.keyCode == 65 || e.keyCode == 67 )
&& e.ctrlKey));
// don't search when user hits Ctrl+A or Ctrl+C
checkAlphabet = ((ctrlCombine == false) ? checkAlphabet : false);
if (checkAlphabet || checkNum || checkBackspaceEnter) {
var dataTable = $('.table').DataTable();
dataTable.search(this.value).draw();
}
}
});
});
Use regular expressions with preg_replace to remove letters other than alpha-numeric on every keyup and then check the length of a string.
Hope you get the desired result.

jQuery prevent writing letters and change comma to dot

I have tried to modify this code but it just wont work...probably some small mistake but i can't debug it :(
// replace , with . and block writing letters
$(document).on("keydown", ".amount", function () {
$(this).keydown(function(e) {
if(e.keyCode==188 || e.keyCode==110 || e.keyCode==108){
e.preventDefault();
$(this).val($(this).val() + '.');
}
var key = e.charCode || e.keyCode || 0;
return (key == 8 || key == 9 || key == 46 || key == 110 || key == 188 || key == 190 || (key >= 35 && key <= 40) || (key >= 48 && key <= 57) || (key >= 96 && key <= 105));
});
};
This is original code and it doesn't work on dynamic content
that is why i want to modify it!
How about just calling your ForceNumericOnly method when the user clicks into an input with .amount?
$(document).on('focus', '.amount', function(){
$(this).ForceNumericOnly();
});
https://jsfiddle.net/daveSalomon/r5n8xuhx/5/
You could (should) optimise it so it doesn't add the keydown handler again if it's already run the ForceNumericOnly code... something like:
$.fn.ForceNumericOnly = function() {
return this.each(function() {
if($(this).data('forceNumberOnly'){ return; }
$(this).data('forceNumberOnly',true);
...
});
};
https://jsfiddle.net/daveSalomon/r5n8xuhx/6/
There's no JS required - just use a number input:
<input class="amount" type="number">

jQuery replace comma with dot doesn't work

I have tried to append the code from another post which works perfectly on fiddle on this link: http://jsfiddle.net/WfpEu/51/
The code replaces comma "," as soon as the user types it and turns it to dot "."
$.fn.ForceNumericOnly = function() {
return this.each(function() {
$(this).keydown(function(e) {
if(e.keyCode==188 || e.keyCode==110 || e.keyCode==108){
e.preventDefault();
$(this).val($(this).val() + '.');
}
var key = e.charCode || e.keyCode || 0;
return (key == 8 || key == 9 || key == 46 || key == 110 || key == 188 || key == 190 || (key >= 35 && key <= 40) || (key >= 48 && key <= 57) || (key >= 96 && key <= 105));
});
});
};
$(".item").ForceNumericOnly();
I have tried to append it to my code here http://jsfiddle.net/p2Hbm/104/ and it doesn't work as it should and i don't know what is wrong. I can't write letters in input fields which is good but also i can't write comma "," it doesn't show up at all.
You need to add the itemclass to your input fields.
Working fiddle: http://jsfiddle.net/p2Hbm/106/

Need to replace "comma" with 'dot'

Please help me to adjust an existing script to replace COMMA with DOT.
I use a script which limit the inserting character into Text fields. Only 1,2,3,4,5,6,7,8,9,0 and "." and "," are accepted to be inserted. I would like to have two buttons of inserting DOT - key==188 (comma) and key== 190 (dot).
jQuery.fn.ForceNumericOnly =
function()
{
return this.each(function()
{
$(this).keydown(function(e)
{
var key = e.charCode || e.keyCode || 0;
return (
key == 8 ||
key == 9 ||
key == 46 ||
key == 110 ||
key == 188 ||
key == 190 ||
(key >= 35 && key <= 40) ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
});
});
};
$("#iMONEY").ForceNumericOnly();
It can be tested HERE
Just use
if(e.keyCode == 188){
e.preventDefault();
$(this).val($(this).val() + '.');
}
Here you go. :)
For future references Mini-Tutorial.
The value of the textbox is updated after keypress event is fired. It's not a place to replace comma with dot. Use keyup event instead:
jQuery.fn.ForceNumericOnly =
function()
{
this.keyup(function(e)
{
// console.log("Change");
$(this).val($(this).val().replace(/,/g,"."));
});
};
$("#iMONEY").ForceNumericOnly();
DEMO
var key = e.charCode || e.keyCode || 0;
// 110 is numpad comma code
if (key === 188 && key === 110) {
e.preventDefault();
$(this).val($(this).val() + '.');
}
You need to use the Replace method
var someVariable = "1,2,3,4,5,6,7,8,9,0";
$mylabel.text( someVariable.replace(',', '.') );
EDIT:
If you are checking from TextBox then do it like this:
if(Key == 188){
var someVariable = $("#TEXTBOXID").val();
somVariable = someVariable.replace(',', '.');
}

Wrong execution on function in JS

I have this code, but somewhy when i use this function to validate my input field everything works, except + and - keys, even thought i noted them as true. What have i done wrong?
function validateNumber(event)
{
var key = window.event ? event.keyCode : event.which;
if (event.keyCode == 8 || event.keyCode == 46 || event.keyCode == 37 ||
event.keyCode == 39 || event.keyCode == 107 || event.keyCode == 109 ||
event.keyCode == 32 )
{
return true;
}
else if(key < 48 || key > 57)
{
return false;
}
else return true;
};
I don't see you checking for 189 (-) and 187 (=, which is really what happens when you type +). You might want to check if the Shift key is pressed for +.
As already noted, it's overall a wrong way to validate user input. You need to inspect the value of the input, not individual keystrokes.
First, define a validation function that would check an arbitrary text with a regexp:
function checkArithmetic(str) {
var regexp = /^[0-9+-]$/;
return regexp.test(str);
}
Next, add a handler to your input element:
input.addEventListener('input', function (e) {
var value = input.value;
if (checkArithmetic(value)) {
// OK!
} else {
// error
}
}, false);

Categories

Resources