Jquery keypress except: {something} - javascript

Is there any shortcut( actually a function) in jQuery or Javascript to handle button press except something, or only something, e.g.:
$(input).keypress('nonfunctional' function(){
// do something
});
that will trigger only on [a-z][0-9] buttons pressed and ignoring single shift or ctrl but handling shift+a => A pressed?
P.S.i do know about if(key.code == 123) then ...

No, if you want to exclude specific keys that's what the event.keyCode / event.which properties are there for.

Or you can extend jquery keypress. Something like this I guess:
$.fn.keypressBut = function(codes, callback) {
$(this).keypress(function(e) {
~$.inArray(e.keyCode, codes) || callback.call(this, e);
});
}
// Lets ignore Enter and Space
$('input').keypressBut([13, 32], function(e) {
alert(e.keyCode);
})

You could do something like
Extend jquerys fn propertie with a function which takes params like
Some Data
A callback function
Write a validation Function which
Converts the keyCode to a String
Match it against a Regular Expression.
If the shiftKey was Pressed
Convert it to Upper Case
Check if other Conditions, like Ctrl/Alt key Pressed are met.
Returns the Result.
If the validation succeeds
execute the callback function
On the code site this could like
$.fn.selectedKey = function (cb, data) {
def.call(data, {
ctrlKey: 2, //0: musn't be pressed, 1: must be pressed, 2: both.
altKey: 2, // "
invert: 0, //inverts the filter
filter: /.*/, // A Regular Expression, or a String with a Regular Expression
preventDefault: false //Set to true to prevent Default.
}); //Sets the default Data for the values used,
function validate(e) {
var key = e.char = String.fromCharCode(e.keyCode || e.which); // Converts the pressed key to a String
if (e.shiftKey) key = key.toUpperCase(); //Handles Case Sensitivity.
var exp = new RegExp(e.data.filter.replace(/\\\\(\d)/g, String.fromCharCode("$1"))); //Creates a new RegExp from a String to e.g. allow "\2" to match the keyCode 2
var c = !! (e.data.ctrlKey ^ e.ctrlKey ^ 1 > 0); //c == true if the above stated conditions are met e.g Ctrl Key Pressed and `ctrlKey == 1` -> true
var a = !! (e.data.altKey ^ e.altKey ^ 1 > 0); //e.g Alt Key Pressed and `altKey == 0` -> false
return (exp.test(key) && (c && a)); //Returns the validation Result
}
function def(obj) { //a minimal helper for default values
for (var prop in obj) {
this[prop] = this[prop] || obj[prop];
}
}
this.keypress(data, function (e) {
if (e.data.preventDefault) e.preventDefault();
if (validate(e) != e.data.invert) cb(e); //Calls the callback function if the conditions are met
});
};
Which you could then use the following ways
With a regex
$("body").selectedKey(function (e) {
console.log("All lower characters Numbers and 'A': " + e.char);
}, {
filter: /[a-z]|[0-9]|A/,
ctrlKey: 2,
altKey: 2
});
This would be triggered if any [a-z] or [0-9] or the Shift key + A has been pressed, regardless of the state of ctrl and alt
Or a keycode
$("body").selectedKey(function (e) {
// do somet
console.log("KeyCode 2 " + e.char);
}, {
filter: "\\2", //Ctrl + b
ctrlKey: 1,
altKey: 2
});
Would be triggered if you press ctrl +b
You could also combine those both.
Heres an Example on JSBin, to fiddle around with.

There is a jQuery plugin for using classes and regex for filtering keypresses if you dont want to write a large if statement to detect the key code pressed, its called keyfilter. An example would be
$(selector).keyfilter(/[a-z]/);

For example this function below allow only numbers en handle this functions using the keydown event.
function OnlyNumbers(event) {
if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 || (event.keyCode == 65 && event.ctrlKey === true) || (event.keyCode >= 35 && event.keyCode <= 39)) { return; }
else { if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) { event.preventDefault(); } }
}

have you tried event.altKey/event.shiftKey/event.ctrlKey ??

Related

Keycode value is return as 229 for all keys

I have run the normal textbox in android device an i have face some issues which is mentioned below.
1.Keypress event does not triggered in android device
2.keycode value always return as 229 only
How to resolve this issue?
Normal keypress event does not give keyCode in android device. There has already been a big discussion on this.
If you want to capture the press of space bar or special chars, you can use keyup event.
$('#input').on('keyup', e => {
var keyCode = e.keyCode || e.which;
if (keyCode == 0 || keyCode == 229) {
keyCode = e.target.value.charAt(e.target.selectionStart - 1).charCodeAt();
}
})
just check your input characters keyCode, if it is 0 or 229 then here is the function getKeyCode which uses charCodeAt of JS to return the KeyCode which takes input string a parameter and returns keycode of last character.
<script>
var getKeyCode = function (str) {
return str.charCodeAt(str.length);
}
$('#myTextfield').on('keyup',function(e){
//for android chrome keycode fix
if (navigator.userAgent.match(/Android/i)) {
var inputValue = this.value;
var charKeyCode = e.keyCode || e.which;
if (charKeyCode == 0 || charKeyCode == 229) {
charKeyCode = getKeyCode(inputValue);
alert(charKeyCode+' key Pressed');
}else{
alert(charKeyCode+' key Pressed');
}
}
});
</script>

Allow arrow keys in Regular Expression

I am performing alphanumeric validation and now I am doing that user can only enter an alphanumeric value and also allow alphanumeric values only while pasting. So I used the following regular expression
function OnlyAlphaNumeric(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if ((charCode > 32 && charCode < 48) || (charCode > 57 && charCode < 65) ||
(charCode > 90 && charCode < 97) || charCode > 122) {
return false;
}
else {
return true;
}
}
And for preventing the copy and paste,
function CPOnlyAlphaNumeric(evt) {
$(evt).val($(evt).val().replace(/[^A-Za-z0-9]/g, ' '))
}
These two functions are calling from the following onkeypress and onkeyup methods such that is given below as shown that
#Html.TextBoxFor(model => model.ProductName, new { #class = "form-
control", #onkeypress = "return OnlyAlphaNumeric(this);", #onkeyup=
"return CPOnlyAlphaNumeric(this);" })
This works for alphanumeric validation, but it doesn't allow the cursor to move left side for editing the text. So what will change I should do in my Regular Expression.
Your problem has nothing related to regular expressions.
When you press any key (including left/right arrow) you take value of input, replace all forbidden characters and set the value of the input. When last action is done it's the browser native behavior to move the cursor to the end of input.
You can check what is the pressed key and if it's left/right arrow to skip the manipulation of input value.
function CPOnlyAlphaNumeric(evt) {
var code = evt.which ? evt.which : event.keyCode;
// 37 = left arrow, 39 = right arrow.
if(code !== 37 && code !== 39)
$(evt).val($(evt).val().replace(/[^A-Za-z0-9]/g, ' '))
}
Demo
However this is not a good solution because it will result in a terrible behavior (you won't be able to use shift for mark, the cursor will be moved at the end after first typed letter in the middle of word etc..)
A better solution could be to 'clean' the input value let's say 500 ms after user stop typing.
var timeout = null;
function CPOnlyAlphaNumeric(evt) {
if(timeout)
clearTimeout(timeout);
timeout = setTimeout(function(){
$(evt).val($(evt).val().replace(/[^A-Za-z0-9]/g, ' '))
}, 500);
}
Demo
Please note that you need to add the validation on server side as well (and maybe before the form submit, because user can hit enter to submit the form before the 'cleaning' of input is triggered).
You can try this, it may solve your problem.
var regex = new RegExp("^[a-zA-Z0-9]+$");
var charCode =(typeof event.which == "number") ?event.which:event.keyCode
var key = String.fromCharCode(charCode);
if (!(charCode == 8 || charCode == 0)) {
if (!regex.test(key)) {
event.preventDefault();
return false;
}
}
Problem with keyDown event is that you cant suppress the display of keys in the textfield (only alpha numeric in my case). You can do it in only keyPress event. But you cant get navigation keys in keyPress event, you can only track them in KeyDown event. And some of the keys $,%, have the same e.which that arrow keys has in keypress event. which is causing issues for me to write the logic to allow arrow keys but restrict the text to only Alpha numeric. Here is the code I came up with. Working fine now.
onKeyPress: function(e){
var regex = new RegExp("^[a-zA-Z0-9\b ]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
var allowedSpecialKeys = 'ArrowLeftArrowRightArrowUpArrowDownDelete';
var key = e.key;
/*IE doesn't fire events for arrow keys, Firefox does*/
if(allowedSpecialKeys.indexOf(key)>-1){
return true;
}
if (regex.test(str)) {
return true;
}
e.preventDefault();
e.stopPropagation();
e.cancelBubble = true;
return false;
}

wrong ASCII key code for delete key

I have an HTML form in which I need to allow only numeric key-press. For this i have used the following code
$(".span8").keypress(function(e)
{
var unicode=e.charCode? e.charCode : e.keyCode
//alert(unicode);
if ((unicode ==8) || (unicode==9)|| (unicode==46)){
//if the key isn't the backspace key (which we should allow)
}
else
{
if (unicode<48||unicode>57&&unicode!=65) //if not a number
return false //disable key press
}
});
but here if I am testing keycode, I am getting value as 46 for delete key. 46 is for dot(- period)
Others values are coming correct. I am not able to find were am I going wrong.
Please help
I've found this weird behaviour too with the keypress function.
Instead, try the following:
jQuery(function($) {
var input = $('.span8');
input.on('keydown', function() {
var key = event.keyCode || event.charCode;
if(key == 8 || key == 46)
//Do something when DEL or Backspace is pressed
});
});

Use JavaScript to allow only specific characters in HTML input

I have written some JavaScript and jQuery code that accepts only numeric input in a textbox.
But this is not enough; I need to limit the input to certain numbers.
This textbox needs to deal with SSN numbers (Swedish SSN), and it has to start with 19 or 20. I want to force it to start with these numbers, but I can't manage to limit it to these.
$('input.SSNTB').keydown(function (event) {
var maxNrOfChars = 12;
var ssnNr = $('input.SSNTB').val();
if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 ||
// Allow: Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
else {
// Ensure that it is a number and stop the keypress
if (((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105))) {
console.log("if-1");
event.preventDefault();
}
if (event.shiftKey == true) {
console.log("if-3");
event.preventDefault();
}
//rules to make sure the textbox starts with correct number
if (event.keyCode != 49 || event.keyCode != 50 || event.keyCode != 97 || event.keyCode != 98) {
console.log("if-4, Keycode:" + event.keyCode);
event.preventDefault();
}
}
});
The last if-case is executed to for testing this it is. It is executed as planed but it wont limit the input chars as its built for.
any tips or ideas?
You can use regex to limit the user to only inputting numbers and dashes. Using regex has the advantage that users can more naturally interact with the input, for instance they can paste into the text input and it will be validated successfully:
//bind event handler to the `keyup` event so the value will have been changed
$('.SSNTB').on('keyup', function (event) {
//get the newly changed value and limit it to numbers and hyphens
var newValue = this.value.replace(/[^0-9\-]/gi, '');
//if the new value has changed, meaning invalid characters have been removed, then update the value
if (this.value != newValue) {
this.value = newValue;
}
}).on('blur', function () {
//run some regex when the user un-focuses the input, this checks for the number ninteen or twenty, then a dash, three numbers, a dash, then four numbers
if (this.value.search(/[(20)(19)](-)([0-9]{3})(-)([0-9]{4})/gi) == -1) {
alert('ERROR!');
} else {
alert('GOOD GOING!');
}
});
Here is a demo: http://jsfiddle.net/BRewB/2/
Note that .on() is new in jQuery 1.7 and in this case is the same as using .bind().
Thought I would post the solution that came to the end. I actually kept the similar code that I posted above and did not covert this it RegExp. What was done was to verify the number after focus on this textbox is lost. It it is incorret the user will be informed and forced to fill in a valid number.
$('input.SSNTB').focusout(function () {
var ssnNr = $('input.SSNTB').val();
var ssnNrSub = ssnNr.substring(0, 2);
//console.log(ssnNrSub);
//checks for correct lenggth
if (ssnNr.length < 12) {
$('div.SSNHelp label.Help').html('SSN to short. Please fill in a complete one with 12 numbers');
setTimeout(function () {
$('input.SSNTB').focus();
}, 0);
validToSave = false;
return;
}
//checks so it starts correct
if (ssnNrSub != "19" && ssnNrSub != "20") {
$('div.SSNHelp label.Help').html('The SSN must start with 19 or 20. Please complete SSN.');
setTimeout(function () {
$('input.SSNTB').focus();
}, 0);
validToSave = false;
return;
}
$('div.SSNHelp label.Help').html('');
validToSave = true;
});
Works for me. : ]
You have to use regex. Regex is of help in these kind of situations.
Learn more about it from https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp

JavaScript Key Codes

I'm working with a JavaScript routine I didn't write. It is called from a text box's onkeydown attribute to prevent unwanted keystrokes.
The first argument is apparently not used. The second argument is a list of characters that should be allowed.
function RestrictChars(evt, chars) {
var key;
var keychar;
if (window.event)
key = window.event.keyCode;
else if (e)
key = e.which;
else
return true;
keychar = String.fromCharCode(key);
if ((key == null) || (key == 0) || (key == 8) ||
(key == 9) || (key == 13) || (key == 27))
// Control key
return true;
else if (((chars).indexOf(keychar) > -1))
return true;
else
return false;
}
This seems to work for alpha-numeric characters. However, characters such as . and / cause this function to return false, even when these characters are included in the chars parameter. For example, if the . key is pressed, key is set to 190, and keychar gets set to the "3/4" character.
Can anyone see how this was meant to work and/or why it doesn't? I don't know enough about JavaScript to see what it's trying to do.
Two things are wrong with that: first, if you're analysing what character has been typed, you need to use the keypress event instead of keydown because that is the only event that tells you anything reliable about the actual character typed. For (a lot) more detail about about this and JavaScript key events in general, see http://unixpapa.com/js/key.html. Second, there are references to a variable called e which doesn't (but should) correspond with the evt parameter.
Here's a rewrite, assuming you have a variable called textBox that refers to the text input element.
jsFiddle: http://jsfiddle.net/9DZwL/
Code:
function isKeypressCharValid(e, chars) {
e = e || window.event;
// Allow delete, tab, enter and escape keys through
if (/^(8|9|13|27)$/.test("" + e.keyCode)) {
return true;
}
var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
var charTyped = String.fromCharCode(charCode);
return chars.indexOf(charTyped) > -1;
}
textBox.onkeypress = function(evt) {
if (!isKeypressCharValid(evt, "abc123")) {
return false;
}
};
I'm not a JS person, either, but... I can explain how it's supposed to work; I don't know why you're getting the values you are for the keys you mentioned, however.
keychar = String.fromCharCode(key);
This checks to see if the key is a printable character (letter, punctuation mark, etc.)
if ((key == null) || (key == 0) || (key == 8) ||
(key == 9) || (key == 13) || (key == 27))
// Control key
The above checks to see if the key is null OR (||)` 0 or 8 (backspace) or 9 (tab) or 13 (0x0D, or ENTER) or 27 (0x1B or ESCAPE) - it's exactly the Boolean result you'd expect: IF <thiscondition> or <thatcondition> or <anothercondition> or ...
else if (((chars).indexOf(keychar) > -1))
This checks to see if the keychar is in the string of characters passed as the chars parameter

Categories

Resources