RegExp TAB in Firefox - javascript

This code works in all popular browsers except Mozilla Firefox. The problem is that the TAB-key doesn't work. Can anyone figure out why? It's connected to a form of text fields. I've tried adding '\t', didn't work. It works in all browsers for me, except Firefox...
$('.mail').bind('keypress', function (event) {
var regex = new RegExp("^[a-zA-Z0-9#\S._\n\r\b-]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});

without going into the regular expression, you can easily allow the tab keypress by comparing against its code:
$('.mail').bind('keydown', function (event) {
var regex = new RegExp("^[a-zA-Z0-9#\S._\n\r\b-]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key) && event.which != 9) {
event.preventDefault();
return false;
}
});
If you run into more cases that should work but don't it might be good to revisit the regex but if that's the only case then this quick workaround should be enough.
Also note I'm using keydown instead of keypress (event.which throws different codes on keypress)
jsfiddle

Related

Mozilla firefox version 64: Kepress event called for keys like tab, backspace , arrowkeys etc

#HostListener('keypress', ['$event']) onKeyPress(event: KeyboardEvent) {
const key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
let isValidExp = true;
if (!this.expression.test(key)) {
isValidExp = false;
}
return isValidExp;
}
Above piece of snippet calls for the keys like backspace, arrowkeys etc. Resulting it is returning false and keys are not working as expected. This is happening in Mozilla Firefox (version 64) Windows 8.1
I know i can have set of keycodes and based on that i can return true. But can someone help me with this issue to be more generic solution to avoid all these kind of scenarios. Kindly help.

Get the keypress code without to care which symbol is clicked using JQuery

I see here is have few questions when is asking for how can get which key is clicked from keyboard. I tested is ok is working if is in English case.
If I change the language and the symbols on keyboard is changed then is not show anything.
So my question is how can I get the keypress code without to care which language is now used the user when is click the key 'G' or 'Г' or something else.
here is my simple jquery code
$(document).keypress(function(e) {
if (e.charCode == 103) {
alert('g');
} else if (e.charCode == 71) {
alert('G');
}
});
If is with english is working, when I change to Bulgarian then is not working. How can I make to working on every language?
Using the keypress event will give you the character typed, regardless of keyboard layout.
For character input, it is suggested you use keypress(), which will report the actual ASCII code for the character pressed. It automatically takes care of letter case, and ignores non-character presses. In either case, you can use fromCharCode() to convert to a string representation. E.g.
document.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charTyped = String.fromCharCode(charCode);
alert("Character typed: " + charTyped);
};
I find the solution of my problem. Thanks of this article
$(document).on('keydown', function(e) {
if (e.ctrlKey) {
alert('Echo');
} else {
alert(e.which + ' ' + e.key);
}
});
What I'm changing. I change only the event. I replace 'keypress' with 'keydown' and now is the same code without to care which language is used.

consistent keyCode for `#`

While I know that capturing keys due to the e.keyCode vs e.charCode is not trivial, I thought that jQuery would pretty much be able to normalize most of those inconsistencies.
However while answering this question I found out that the character # seems to have very inconsistent keyCodes (and of course this is true for several other codes also, mostly depending on the browser and keyboardlayout I guess).
Chrome and IE yielded 191, Firefox 163 on my computer, another user reported 222. Chromes window.event even reported U+00BF as keyIdentifier - which according to unicode tables should be ¿.
Do you know any consistent way to determine such symbols like the # with inconsistent keyCodes without doing something nasty like the following:
$('input').keydown(function (e) {
if (e.which == 191 || e.which == 163 || e.which == 222){
// hope you got the right key
e.preventDefault();
}
});
Fiddle for your pleasure.
This works for me in Chrome and Firefox with a US keyboard:
$('[id$=txtClient]').keypress(function (e) {
if (String.fromCharCode(e.which) == '#') {
e.preventDefault();
}
});
keypress is the only event that will give you reliable info on the character that was entered.
Demo: http://jsfiddle.net/elclanrs/ebcet/9/
Have you tried using the keypress event ?
The documentation warns about possible differences in behavior between platforms.
In Firefox at least, e.which corresponds to the ascii code of the typed character after transformation :
$('#txtClient').keypress(function (e) {
console.log('keypress:', e.which);
if (e.which == 35) {
return false;
}
});
updated fiddle

JavaScript KeyCode Values are "undefined" in Internet Explorer 8

I'm having trouble with some JavaScript that I've written, but only with Internet Explorer 8. I have no problem executing this on Internet Explorer 7 or earlier or on Mozilla Firefox 3.5 or earlier. It also executes properly when I use compatibility mode on Internet Explorer 8.
What I'm doing is overriding the Enter keystroke when a user enters a value into a textbox. So on my element I have this:
<asp:TextBox ID="ddPassword" runat="server" TextMode="Password" onkeypress="doSubmit(event)" Width="325"></asp:TextBox>
And then I have the following JavaScript method:
function doSubmit(e)
{
var keyCode = (window.Event) ? e.which : e.keyCode;
if (keyCode == 13)
document.getElementById("ctl00_ContentPlaceHolder1_Login").click();
}
Again, this all works fine with almost every other browser. Internet Explorer 8 is just giving me a hard time.
Any help you might have is greatly appreciated.
UPDATE: Thanks everyone for your quick feedback. Both Chris Pebble and Bryan Kyle assisted with this solution. I have awarded Bryan the "answer" to help with his reputation. Thanks everyone!
It looks like under IE8 the keyCode property of window.Event is undefined but that same property of window.event (note the lowercase e) has the value. You might try using window.event.
function doSubmit(e)
{
var keyCode = (window.event) ? e.which : e.keyCode;
if (keyCode == 13)
document.getElementById("ctl00_ContentPlaceHolder1_Login").click();
}
Just a hunch, try this:
var keyCode = e.keyCode ? e.keyCode : e.which;
It's worked on this way on my code:
var kcode = (window.event) ? event.keyCode : event.which;
try this:
function checkKeyCode(e){
if (!e) e = window.event; var kCd = e.which || e.keyCode;
return kCd;
}
I personally prefer the multi-key approach. This allows multiple keys to be detected, but also a single key just the same, and it works in every browser I've tested.
map={}//declare object to hold data
onkeydown=onkeyup=function(e){
e=e||event//if e doesn't exist (like in IE), replace it with window.event
map[e.keyCode]=e.type=='keydown'?true:false
//Check for keycodes
}
An alternative method would be to separate the onkeydown and onkeyup events and explicitly define the map subitems in each event:
map={}
onkeydown=function(e){
e=e||event
map[e.keyCode]=true
}
onkeyup=function(e){
e=e||event
map[e.keyCode]=false
}
Either way works fine. Now, to actually detect keystrokes, the method, including bug fixes, is:
//[in onkeydown or onkeyup function, after map[e.keyCode] has been decided...]
if(map[keycode]){
//do something
map={}
return false
}
map[keycode] constitutes a specific keycode, like 13 for Enter, or 17 for CTRL.
The map={} line clears the map object to keep it from "holding" onto keys in cases of unfocusing, while return false prevents, for example, the Bookmarks dialog from popping up when you check for CTRL+D. In some cases, you might want to replace it with e.preventDefault(), but I've found return false to be more efficient in most cases. Just to get a clear perspective, try it with CTRL+D. Ctrl is 17, and D is 68. Notice that without the return false line, the Bookmarks dialog will pop up.
Some examples follow:
if(map[17]&&map[13]){//CTRL+ENTER
alert('CTRL+ENTER was pressed')
map={}
return false
}else if(map[13]){//ENTER
alert('Enter was pressed')
map={}
return false
}
One thing to keep in mind is that smaller combinations should come last. Always put larger combinations first in the if..else chain, so you don't get an alert for both Enter and CTRL+ENTER at the same time.
Now, a full example to "put it all together". Say you want to alert a message that contains instructions for logging in when the user presses SHIFT+? and log in when the user presses ENTER. This example is also cross-browser compatible, meaning it works in IE, too:
map={}
keydown=function(e){
e=e||event
map[e.keyCode]=true
if(map[16]&&map[191]){//SHIFT+?
alert('1) Type your username and password\n\n2) Hit Enter to log in')
map={}
return false
}else if(map[13]){//Enter
alert('Logging in...')
map={}
return false
}
}
keyup=function(e){
e=e||event
map[e.keyCode]=false
}
onkeydown=keydown
onkeyup=keyup//For Regular browsers
try{//for IE
document.attachEvent('onkeydown',keydown)
document.attachEvent('onkeyup',keyup)
}catch(e){
//do nothing
}
Note that some special keys have different codes for different engines. But as I've tested, this works in every browser I currently have on my computer, including Maxthon 3, Google Chrome, Internet Explorer (9 and 8), and Firefox.
I hope this was helpful.
Try adding onkeyup event as well and call the same function.
TIP:
You can add debugger; at beginning of doSubmit to set a break, then you can examine keyCode.
I think window.Event.keyCode works in IE8 (I can't test right now though)
Or something like that.
var keyCode = e.which || e.keyCode;

event is not defined in mozilla firefox for javascript function?

function onlyNumeric() {
if (event.keyCode < 48 || event.keyCode > 57) {
event.returnValue = false;
}
}
onkeypress=onlyNumneric();
In IE, this code is working fine. However, in Mozilla Firefox, the event is an undefined error.
In FF/Mozilla the event is passed to your event handler as a parameter. Use something like the following to get around the missing event argument in IE.
function onlyNumeric(e)
{
if (!e) {
e = window.event;
}
...
}
You'll find that there are some other differences between the two as well. This link has some information on how to detect which key is pressed in a cross-browser way.
Or quite simply, name the parameter event and it will work in all browsers. Here is a jQueryish example:
$('#' + _aYearBindFlds[i]).on('keyup', function(event) {
if(! ignoreKey({szKeyCodeList: gvk_kcToIgnore, nKeyCode: event.keyCode })) this.value = this.value.replace(/\D/g, '');
});
This example allows digits only to be entered for year fields (inside a for each loop selector) where ingoreKey() takes a keyCode list/array and compares the event keyCode and determines if it should be ignored before firing the bind event.
Keys I typically ingore for masks/other are arrow, backspace, tabs, depending on context/desired behaviour.
You can also typically use event.which instead of event.keyCode in most browsers, at least when you are using jQuery which depends on event.which to normalize the key and mouse events.
I don't know for sure what happens under the covers in the js engines, but it seems Mozilla FF respects a stricter scope, wherein, other browsers may be automatically addressing the window.event.keyCode scope on their own when the event is not explicitly passed in to a function or closure.
In FF, you can also address the event by window.event (as shown in some examples here) which would support this thought.
Some browsers may not support keyCode you have to use keyChar
function onlyNumeric() {
var chars = event.keyCode | event.keyChar;
if (chars < 48 || chars > 57) {
event.returnValue = false;
}
}
onkeypress=onlyNumneric();

Categories

Resources