We are trying to prevent users from typing beyond the maximum characters our DB allows for text area fields in our web app. Once they have reached the max length allowed in the text area we would still like to allow them to hit keys that are non-printing for example: Tab, backspace, ctrl+s, etc.
I'm wondering if there is a simple way to detect if a keycode is a printable character. I thought something like String.fromCharCode might do the trick and return false if it couldn't do the conversion, but doesn't seem to behave that way.
You could just set length of the textbox to the max number of characters allowed by the database
W3Schools
Try this: http://www.quirksmode.org/dom/maxlength.html
Quirksmode goes through an easy way to implement the maxlength attribute on textareas, which isn't natively supported.
And to directly answer your question:
var character = String.fromCharCode(e.charCode);
Where e is the event object of the keypress event.
Related
char is deprecated
charCode is deprecated
key fires for both printable characters and control keys
keyCode is deprecated
which is deprecated
keypress is deprecated
input does not fire for elements that are not input, textarea, select or contenteditable - most annoyingly tabindex is not enough
Is the recommended way going forwards to keep the list of predefined key values as a blacklist and assume what's not on there is a printable character? How's that going to work out for keyboards with special/programmable keys?
When trying to capture printable characters on non-input|textarea|select|contenteditable, is as of current the only non-hacky (no incomplete ranges or blacklists as seen in many similar questions) way without using deprecated features to use a hidden input/textarea and use its value for capturing characters that actually change that value?
As a pragmatic solution use key:
assume that all single-character key names are printable
currently true except for space: " "
https://developer.mozilla.org/en/docs/Web/API/KeyboardEvent/key/Key_Values
check that no modifiers were pressed (https://stackoverflow.com/a/4194212)
Example code:
const isPrintableChar = e.key.length === 1 && e.key !== ' ';
const noModifier = !e.ctrlKey && !e.metaKey && !e.altKey;
return isPrintableChar && !noModifier;
For backward compatibility, consider using e.which as a fallback.
Okay after looking into it for some time, the answer is: You can't determine this without relying on deprecated APIs or textarea hack.
Of course these are unlikely to ever go away, but if someone ends up looking for a way to do this without them, they won't find one.
A partial solution is a blacklist of the key values, but it's only a question of a new TV coming out with a quirky remote with extra proprietary keys or something like that and all bets are off.
I'm trying to catch the character inserted before it shows on the screen to validate the screen. See my code
_this.on('keypress keydown',function(e){
var t = e.target;
var k = e.which || e.keyCode;
var c = String.fromCharCode(k);
console.log(String.fromCharCode(k))
});
If I for example type ~ or any other punctuation characters, it returns non-latin characters, such as å. I'm on Chromium, Ubuntu.
I noticed that the keypress is being ignored with these special characters, what is a shame and that's why I am trying with keydown as well. But keydown fails to detect the right character and converts them to scandinavian and asian characters.
Is there a workaround to get the correct character being yped?
See this wonderful answer to a similar question, and the associated jsfiddle: http://jsfiddle.net/S2dyB/17/
One problem is that the keypress and keydown events are not interchangeable. keypress is used to retrieve the actual character that was typed (so special keys are ignored), while keydown returns a unique character code for each key on the keyboard. To exacerbate this, different browsers handle each event a little bit differently, making it a big mess.
Take a look at how e.which varies between keydown and keypress: http://jsfiddle.net/9TyzP/
As you can see, they rarely match up--and with many keys, the displayed code for keypress doesn't change at all, indicating that the event did not fire for that key.
I have a special use case where I have a series of input fields, and I switch from the current input field to the other based on the character typed. Its something like a keyword search where keywords are space separated or are enclosed in double quotes. So, as soon as I close a double quote around a word like "India", it should become a keyword and the focus should move to the next input field.
Now, I'm using a Mac with the US - International (PC) keyboard layout which allows me to type accented characters. For example, " + e = ë.
What happens now, is if I type something like "what" and after the second quote, I hit space, the focus moves to the new input field perfectly, BUT, the new input field already has a " character pre-filled in it!
Some debugging showed that this keyboard layout causes two keyup events to be fired, one when you type " and the next when you type space. The event.keyCode for both these events (jQuery) is 229, and in the first case, event.shiftKey is true, and its false in the next. The same holds for when you type " + e, the second event.keyCode is 229 again, which doesn't match ë.
That helps me differentiate between the two events, but I'm looking for a more concrete fix for this. As of now, I've not been able to solve this.
If anyone has any ideas, it'll be great.
I've solved the problem myself. The idea is to differentiate between the two events based on event.shiftKey. When someone types a double quote and intends to type it, event.shiftKey is true. The second event, after the double quote, if someone presses a character that results in the double quote and the new character being combined to an accented character, the new fired event doesn't have shiftKey = true, but event.keyCode = 229 (which is the same), so this can be used to differentiate. If a new input field still receives a phantom ", amends can be made after such two events are detected.
I have the following jQuery event listener to get the key pressed in a text box:
$("#theInput").keyup(function (e) {
var charCode = e.keyCode || e.which;
alert(charCode);
/* rest of the code */
});
My problem is how to accurately get the code for the letter typed. For instance, if I press the a key it will alert '65' - regardless of whether it was a or A. If I switch the input language to a foreign language (e.g. Japanese, Chinese, Thai) and press the a key, it still returns '65' rather than a different code to let me know the foreign character.
Is there a way to I fix this so it gives the correct language and case of the letter?
Have you read the jQuery doco on how the keyup and keydown events work? They are supposed to return a key code (rather than a character code) without regard for whether shift was down at the time, though the event object does have a shiftKey property to tell you whether shift was down. keyup lets you distinguish between different keys associated with the same character, so you can tell whether a digit was entered via the numeric keypad or not.
The event you want is keypress, which returns a character code that differentiates between upper and lower case. Though having said that I'm not sure how it works for foreign languages, and in any case the whole approach doesn't allow for the user entering other text by pasting from the clipboard so that's something else you need to consider.
(By the way, jQuery normalises the event.which property so you shouldn't need to bother checking event.keyCode first.)
Keys are the same regardless of the language. You could get the case with .shiftKey, but the most reliable way is to save the actual characters:
$('#input').keyup(function(e){
var character = this.value.slice(-1)
console.log(character)
})
This is overly simplified, though, as text can be typed somewhere other than the end. You'd have to find the cursor position and then get the respective char.
I need to implement a keyboard for my language. For example, I want that if you type "a" then in the textbox or input box will show: ka http://cl.cooltext.com/rendered/cooltext530153213.png.....If i press "m" it will show:
Now, this is not possible in current webbrowsers because there is no hooking functionality here. For this,I have decided that this algorithm:
Detect keycode of the typed letter (in this case "a")
Maintain a keymap and found from the keycode (in step1) which key will be replaced by "a"
Replace the textarea/textInput as: "string before --a--"+ replaced key from step2 + "rest of the portion after --a--"
return false so that "a" is not written into the textarea/textInput by the browser.
I am searching for a better idea than running substring method after keystroke...Please help.
I've provided code to do just this on Stack Overflow before: show different keyboard character from the typed one in google chrome and Can I conditionally change the character entered into an input on keypress?, for example.
Your algorithm is exactly the correct way to implement this.