Numbers-only JavaScript Firefox solution - javascript

I need some help cleaning up a popular piece of vanilla JavaScript code that causes issues in Firefox.
The following which/keyCode check seems to be about the most popular vanilla JS solution to allow only numbers into an input or textarea.
var charCode = (e.which) ? e.which : e.keyCode;
if (charCode > 31 && ( charCode < 48 || charCode > 57)) {
return false;
}
return true;
Called via onkeypress="return function(event);" on the tag.
However, Firefox apparently binds arrow keys to onkeypress calls, rather than just to onkeyup and onkeydown like other browsers. This means that e.g. the left arrow key's charCode is 37, but so is the charCode for % (shift+5). Even more importantly, it means that the arrow keys can't be used for navigation (moving the caret/text cursor left or right).
However, the difference is that the left arrow key has keyCode 37, while % has the charCode and which of 37 (as shown on http://www.asquare.net/javascript/tests/KeyCode.html). So I was able to make the arrow keys work just fine by doing the following:
if (charcode > 31 && (charcode < 48 || charcode > 57)) {
if (e.keycode && e.keyCode > 36 && e.keyCode < 41) {
return true;
}
return false;
}
return true;
However, I feel like this is not the best or cleanest way to do it, and that there might be more keys handled differently by Firefox than just the arrow keys. What would be a cleaner vanilla JS solution or way to check for at least the arrow keys within this function?
Many thanks!
EDIT: I just figured that even though the code solves it for Firefox, it introduces a new problem for all other browsers, in that these now allow charCodes 37-40 (i.e. %) to be entered. Seems that instead of checking the keyCode, it would need to check the charCode or which, in otherwise the same manner.

I would advise against blocking certain keys, as I feel it degrades the user experience. But given that this is what you need, I would suggest to not rely on the keyCode property. Not only are there compatibility problems related to it, it also does not cover all ways input can be made, like with the mouse and context menu, and is deprecated:
This feature has been removed from the Web standards.
The KeyboardEvent.keyCode read-only property represents a system and implementation dependent numerical code
Instead I propose to use the input event, which triggers on every change to the input value, and then to clean the value of non-digits, while putting the cursor at the place where the first offending character was found. This gives about the same user-experience, and has no bad effect on how arrow keys, backspace, delete, selection, ... etc work:
document.querySelector('#num').addEventListener('input', function() {
var badCharPos = this.value.search(/\D/);
if (badCharPos == -1) return; // all OK
// remove offending characters:
this.value = this.value.replace(/\D/g, '');
this.setSelectionRange(badCharPos, badCharPos);
});
<input id="num">

Related

Number field that deletes non-numbers without clearing previous numbers?

I am using:
<input type="text" onkeyup="this.value = this.value.replace(/\D/g, '')">
I use it to prevent the user from entering anything except a number into a field on my page. However, I noticed that if the user types a number first but then accidentally hits a non-number key, the field is cleared and they have to start over. This may cause frustration so I was wondering if there was a way to tweak the code so that it does not do this, or if there was a similar method I could use. I am limited to JavaScript, JQuery, and HTML. Any help would be appreciated! :)
I found a solution for my issue. I got rid of the code above and ended up using a JS function. I put in within my $(Document).ready(function() I hope this helps someone with the same problem!
$("#medianSalary").keydown( function(event) { if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) { event.preventDefault();} }); });

including two functions in a javascript keypress

As a standard feature I keep a "don't allow returns" on form text fields using:
keypress="return event.keyCode != 13"
However I need to also only allow a numeric value in some field items using:
keypress="return inputLimiter(event,'Numbers')"
which ties in with a function.
So I need to tie the two together in the same keypress but can't find anything on if this is possible and when I've tried combining them neither work.
Combine them with &&.
Using the same style syntax as you used in the question:
keypress="return event.keyCode != 13 && inputLimiter(event,'Numbers')"
In "real" JS:
window.onkeypress = function(){
return event.keyCode != 13 && inputLimiter(event,'Numbers');
};

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