This was an example from our prof and my HTML is rusty so I'm not sure exactly what is going on.
For the form input:
<input type="text" name="widgets" id="widgets" size="2" value="0" onchange="calc();" onkeypress="return isNumberInput(this, event);" />
For the Javascript:
function isNumberInput(field, event)
{
var key, keyChar;
if (window.event)
key = window.event.keyCode;
else if (event)
key = event.which;
else
return true;
// Check for special characters like backspace
if (key == null || key == 0 || key == 8 || key == 13 || key == 27)
return true;
// Check to see if it.s a number
keyChar = String.fromCharCode(key);
if (/\d/.test(keyChar))
{
window.status = "";
return true;
}
else
{
window.status = "Field accepts numbers only.";
return false;
}
Can someone explain what is going on? I'm not too familiar with window.event, event.which, wondow.event.keyCode, etc. I don't really understand the logic. TIA!
var key, keyChar; // declare variable to be used
if (window.event) // window.event Microsoft uses window.event. Does it exist? If so continue
key = window.event.keyCode; // Microsoft uses window.event.keyCode to get the key the was pressed
else if (event) // other modern browsers will create an event object for you to use
key = event.which; // event.which is the key that was pressed
else // else we can't get to the key maybe this is a full text browser? Anyways, no good exit function
return true;
Basically, this code prevents the user from entering anything except a digit in the text field. The function returns true to allow the user to enter the keystroke, and false to prevent it. Additionally, special characters are allowed through as well.
As far as the part that is confusing you, this is really old code, designed for older versions of Netscape and IE. With modern browsers, you could just use event.keyCode, but Netscape used to use event.which, and IE used to require you to use window.event. Modern browsers hide the status bar too, making the window.status lines useless.
Related
In a event listener I am using e.key, but it seems it is not supported by many older browsers.
From https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode and https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/which I can read that e.keyCode and e.which are deprecated in favor of e.key, so I want to use e.key, but what should I do when some browsers are not supporting it?
Should I use
const key = e.key || String.fromCharCode(e.keyCode);
It just seems that they don't give me the same results if the key is, for instance, a comma.
You use whichever is supported by checking them all, starting with the preferred e.key which will be supported by all browsers in time
if (e.key) {
var key = e.key;
} else {
var code = e.which || e.keyCode;
var key = String.fromCharCode(code);
}
They should return the same character
document.getElementById('test').addEventListener('keypress', function(e) {
var code = e.which || e.keyCode;
var key = String.fromCharCode(code);
console.log(key, e.key)
});
<p>Type in the input !</p>
<input id="test">
Note that keyup and keydown events will return different keycodes for certain keys.
I tried implementing e.key in my application because I read on MDN that e.keyCode and e.which are both deprecaenter code hereted as well. However, all I see anywhere is still implementations of e.keyCode || e.which, and that exact code still works everywhere and well for me. MDN does not provide any solution or viable implementation for e.key and I see no key codes anywhere either. I say the documentation is wrong. And as stated here, e.key is NOT the same as e.keyCode or e.which. I would like to know what actually is supposed to be replacing e.keyCode or e.which. I am using it for example, in a keydown event. e.key breaks my code. This is the code:
[...inputs].forEach(input => input.addEventListener('keydown', (e) => {
console.log(Array.isArray([...inputs]))
console.log([...inputs])
const chord = e.keyCode || e.which
if (chord === 8) {
e.preventDefault()
e.currentTarget.value = ''
heading1.innerHTML = `User Registration Form`;
heading1.style.color = `#228b22`;
}
}))
And this is the link to the live application:
User Registration Form Using JS Constraint Validation API
I have received PHP/JS code from previous developer and I need to add number validation to a Mobile Number field. I already have the HTML validation in place but I need to add that if someone presses an invalid key, that it doesn't get displayed only to highlight the field later in red because it contains invalid input.
I've seen many regex's used and tried them but they had an either/or effect from what I need which is: If a letter or special character is entered, do not accept and do not display, all other input (digits, keys) is accepted (I need the invalid character not be displayed at all, not displayed and then erased). The regex that is working the most now is this:
function filterNonDigits(evt)
{
var event = evt || window.event;
var keyentered = event.keyCode || event.which;
keyentered = String.fromCharCode(keyentered);
//var regex1 = /[0-9]|\./;
var regex2 = /^[a-zA-Z.,;:|\\\/~!##$%^&*_-{}\[\]()`"'<>?\s]+$/;
if( regex2.test(keyentered) ) {
event.returnValue = false;
if(event.preventDefault) event.preventDefault();
}
When I used the commented regex1 (with the IF condition reversed), naturally it limited input to only digits thus preventing all keys such as Delete, BackSpace, etc. When using regex2, I still can't press Delete or the digits from the numpad.
So my question is, can the above code be modified to accept only digits but also allow keys? Another important point is that I need a method that doesn't use keycodes (8, 24 etc) for those key, in order to make sure all keyboard types can be used.
New Update:
So my solution is as follows: If the "oninput" property exists, I use the solution provided by Ehtesham and if it doesn't, the backup uses the solution provided by Rohan Kumar. So it's something like this:
if (obj.hasOwnProperty('oninput') || ('oninput' in obj))
{
$('#mobileno').on('input', function (event) {
this.value = this.value.replace(/[^0-9]/g, '');
});
}
else
{
$('#mobileno').on('keypress',function(e){
var deleteCode = 8; var backspaceCode = 46;
var key = e.which;
if ((key>=48 && key<=57) || key === deleteCode || key === backspaceCode || (key>=37 && key<=40) || key===0)
{
character = String.fromCharCode(key);
if( character != '.' && character != '%' && character != '&' && character != '(' && character != '\'' )
{
return true;
}
else { return false; }
}
else { return false; }
});
}
Thanks.
The best method here is to use input event which handles all your concerns. It is supported in all modern browsers. With jQuery you can do like following. Handles all cases pasting the value with mouse/keyboard backspace etc.
$('.numeric').on('input', function (event) {
this.value = this.value.replace(/[^0-9]/g, '');
});
See it here
You can check if input event is supported by checking if the input has this property if not you can use onkeyup for older browsers.
if (inputElement.hasOwnProperty('oninput')) {
// bind input
} else {
// bind onkeyup
}
A nice solution is described in a previous post:
jQuery('.numbersOnly').keyup(function () {
this.value = this.value.replace(/[^0-9\.]/g,'');
});
Try it like,
CSS
.error{border:1px solid #F00;}
SCRIPT
$('#key').on('keydown',function(e){
var deleteKeyCode = 8;
var backspaceKeyCode = 46;
if ((e.which>=48 && e.which<=57) ||
(e.which>=96 && e.which<=105) || // for num pad numeric keys
e.which === deleteKeyCode || // for delete key,
e.which === backspaceKeyCode) // for backspace
// you can add code for left,right arrow keys
{
$(this).removeClass('error');
return true;
}
else
{
$(this).addClass('error');
return false;
}
});
Fiddle: http://jsfiddle.net/PueS2/
Instead of checking for the event keyCode, why don't you just check for changes inside the actual input and then filter out non-numbers?
This example uses keyup so that it can read what was actually entered, which means the character is briefly displayed and then removed, but hopefully you get my gist. It might even give the user feedback that the character is not allowed. Either way I think this is the easiest setup, let me know if you need more help fleshing this out.
function filterNonDigits(evt)
{
var event = evt || window.event;
var val = event.target.value;
var filtered = val.replace(/[^0-9]/g, '');
if(filtered !== val) {
event.target.value = filtered;
event.target.className += " error";
}
}
http://jsfiddle.net/mEvSV/1/
(jquery used solely to easily bind the keyup function, you won't need it for your actual script)
/\d/ is equivalent to the above described /[0-9]/. src: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#special-digit
This is a bit more concise...
this.value = this.value.replace(/\D/gm, '');
I am wondering how to create an event listener, so that when any of the character keys are pressed a form pops up and the first input is in focus and is receiving the input, sort of like the just type search style for the webOS 2.0 operating system, but for a contact form. Is there anyway to do so? In case your not familiar here is a link to the webos just type feature
http://www.youtube.com/watch?v=ixPsB7-tVGo
I don't know if you can only subscribe to letter keys.
Your best bet would be to use jQuery to subscribe to .keydown() / .keyup() and check the keycode of the event to see which letter it is. If it's not a letter, don't do anything.
Like this:
$('#target').keydown(function(event) {
if (event.keyCode >= 65 && event.keyCode <= 90) { // if a letter pressed
// play that funky music.
}
});
More on $.keydown.
List of key codes.
Use the keypress event for anything character related. keydown and keyup cannot be used reliably for this purpose. The following is adapted from my answer to a related recent question:
function isCharacterKeyPress(evt) {
if (typeof evt.which == "undefined") {
// This is IE, which only fires keypress events for printable keys
return true;
} else if (typeof evt.which == "number" && evt.which > 0) {
// In other browsers except old versions of WebKit, evt.which is
// only greater than zero if the keypress is a printable key.
// We need to filter out backspace and ctrl/alt/meta key combinations
return !evt.ctrlKey && !evt.metaKey && !evt.altKey && evt.which != 8;
}
return false;
}
var input = document.getElementById("your_input_id");
input.onkeypress = function(evt) {
evt = evt || window.event;
if (isCharacterKeyPress(evt)) {
// Do your stuff here
alert("Character!");
}
};
I need to detect whether the key which has just been pressed is a printable key, like a character, possibly accented, a number, a space, a punctuation symbol and so on, or a non printable key, like ENTER, TAB or DELETE.
Is there a reliable way to do this in Javascript, other than listing all non printable keys and hope not to forget some?
Luckily, this task is much easier in modern browsers. You can now use KeyboardEvent.key to detect a printable key via its length.
test.onkeydown = e => {
let isPrintableKey = e.key.length === 1;
alert(`Key '${e.key}' is printable: ${isPrintableKey}`);
}
<input id="test">
Besides that, you can also detect any other keys from the list, like Enter, Delete, Backspace, Tab, etc.
This method is much more reliable simply because unlike event.which, event.key is already standardized.
I answered a similar question yesterday. Note that you have to use the keypress event for anything character-related; keydown won't do.
I would argue that Enter is printable, by the way, and this function considers it to be. If you disagree, you can amend it to filter out keypresses with the which or keyCode property of the event set to 13.
function isCharacterKeyPress(evt) {
if (typeof evt.which == "undefined") {
// This is IE, which only fires keypress events for printable keys
return true;
} else if (typeof evt.which == "number" && evt.which > 0) {
// In other browsers except old versions of WebKit, evt.which is
// only greater than zero if the keypress is a printable key.
// We need to filter out backspace and ctrl/alt/meta key combinations
return !evt.ctrlKey && !evt.metaKey && !evt.altKey && evt.which != 8;
}
return false;
}
var input = document.getElementById("your_input_id");
input.onkeypress = function(evt) {
evt = evt || window.event;
if (isCharacterKeyPress(evt)) {
// Do your stuff here
alert("Character!");
}
});
If you need to identify printable key just for change detection as user change the input, you could use oninput event.
let isPrintableKey = event.key.length === 1 || event.key === 'Unidentified';
If you do not include: || event.key === 'Unidentified' your code will not work on mobile browsers.
I try to convert keystrokes into chracters.
In other question someone recommand to use the onkeydown function because onkeypress gets handeled differently by different characters.
I don't know how to handle special chracters like ยด ` ' ( ) that might be different in different keyboards around the world.
For keys that have printable character equivalents, you should use the keypress event because you can retrieve character codes from the keypress event, which is generally not possible for keyup and keydown events.
The event properties you need are which and keyCode - pretty much all browsers have one or both of these, though IE muddies the waters by using keyCode for the character code while some other browsers return a (different) key code. Most non-IE browsers also have charCode but it seems all such browsers also have which, so charCode is never needed. A simple example:
document.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charStr = String.fromCharCode(charCode);
alert(charStr);
};
Here is a useful reference page.
document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
document.getElementById("label").style.display = "none";
if (e.keyCode == '65') {
//a
var lx = document.getElementById('location');
typeIt("a");
}
else if (e.keyCode == '66') {
//b
var lx = document.getElementById('location');
typeIt("b");
}
else if (e.keyCode == '67') {
//c
var lx = document.getElementById('location');
typeIt("c");
}
}
This should successfully convert the key code you press into a string letter, which you can use in a bigger function. It takes more time, but I found it is highly compatible with most browsers and keyboards (whatever the language may be.) I used this code in a text editor project which would be distributed to friends in several countries, so I am certain it will work. Note: the function above only includes the letters "A", "B", and "C".