Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Non-unicode char code to unicode character?

I'm having a character code issue with a barcode scanner used to input characters to a web interface.

If a barcode has a symbol such as - (a dash/hyphen/minus) it gives me character code 189 which is correct in many character sets. Indeed, if I have a text input selected when I do the scan it will enter the - character as expected. However, if I intercept the keypress or keyup event from the global document and use the fromCharCode() function to build the string myself, rather than letting the browser handle it, I get the ½ character which is of course the unicode conversion of the 189 code.

In the event itself both keyCode and "which" show up as 189 while the keyIdentifier is "U+00BD". Unfortunately the charCode value that I really need is always 0.

Now of course I could handle this conversion manually in about 5 seconds right now. The problem is that I don't know the full set of codes that I might get from the scanner and I'm worried about an unhandled character showing up weeks or months into the future and making some headaches. Alternatively, I could upload the raw character codes to the server and try to handle it in PHP. I'd much prefer to handle it on the client for reasons of timing and responsiveness though. Sending fake key presses to an invisible text input would probably work too but that's a really hacky workaround.

It seems like there should be a better way to do this and that I have to be missing something obvious. Does anyone have any ideas?

like image 890
Scott F Avatar asked Oct 09 '13 16:10

Scott F


1 Answers

If you intercept keyboard handling by taking keycodes and interpret them as characters with fromCharCode, you get wrong results, because keycodes simply identify key presses, not characters. The character associated with a key press depends on the keyboard driver.

So the intercepting routine needs to know the keyboard key assignments. You might use common Windows keycodes as a starting point, but then your software will be system-dependent.

like image 88
Jukka K. Korpela Avatar answered Oct 18 '22 04:10

Jukka K. Korpela