Handling double events in accented keyboards - javascript

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.

Related

String.fromCharCode on keypress and keydown are returning wrong characters

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.

How to get the correct language and case for key press in JS event listener?

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.

How to implement this keyboard hooking function in javascript/jquery?

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.

check text area for certain character combinations

I have a text area which gets filled in various ways including paste, keyboard input, from an autocomplete etc.
Now I want to validate this text area and if contains any combination, including multiples of some characters and if so, set it to empty.
The characters I want to filter are: tabs, new lines, spaces, carriage returns, as well as some watermark text - basically any non-meaningful character.
Note that valid text might contain special characters such as ()!#%<>,;:/||{}[] and possibly a few more.
Valid values might contain new lines, spaces etc. but will also have other valid characters (the stuff above plus 0-9, a-z, A-Z etc.)
Currently, I have the following wrapped in a jquery .change event:
<textarea cols="70" rows="3" class="cssTextarea cptEntryArea formFocus"></textarea>
$('.cptEntryArea').live('change', function(e)
{
var myval = "";
myval = $(this).val().trim();
myval.replace(/\r\n|\r|\n|\u0085|\u000C|\u2028|\u2029|^\s*$|^\s+|\s+$/g, "");
if ((myval == watermarkText) || (myval.length == 0))
{
$(this).val("");
e.stopPropagation();
return false;
};
});
The idea is to simply blank it out if it has "non-visual" characters in it in any combination.
Any optimization or better method to get this done?
EDIT1: Looks like I can do some adjustment here as the jQuery trim is:
trim: function( text ) {
return (text || "").replace( /^\s+|\s+$/g, "" );
}
Sounds like a very strange thing to do. What is the watermarkText for? Would it not be a better idea to catch before the text is put into the textarea i.e. on keydown, return null if the ascii value < 33? Your event only fires when the item is changed/lost focus, not immediately when some text is entered.
You could try doing /mg for the regex multi-line.
As it ended up, I had to manage my keystrokes more efficiently as well as the event management of the end result. My solution is a quite complex interactive page where multiple methods are used to populate the value with configurable options of which group of methods and the acceptable values that are allowed, thus the complexity of the resolution.
various methods used to populate the textarea:
Free form (user entered)
Autocomplete - validated against and choosen from a user entered string to produce the select list.
Text MUST match the database exactly
Freeform text allowed, but the associated ID must be in the database
New user text allowed, but must be posted as a new value to the select list
programatic population (pull from database/other value and populate)
All of this makes the validation rules complex however the other answer is being accepted as it best helped resolve the issue.
Note that there are actually multiple keystrokes that get in play here with various actions based on the keystroke and the options in play for a particular user.
Thanks to everyone for the assistance.

How to determine if a keydown event occurs on a printable character?

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.

Categories

Resources