JS Keydown event and Japanese characters

Anyone who works currently with web applications focused on Japanese/Chinese market, will surely sooner or later face a problem with word auto-completion. This exactly happened to me a few days ago, when I was working on a portfolio tagging system. The idea was to show hints with the most common tags starting from the letter user typed. Usually, this is done in JavaScript by listening to an event called “keydown”.

$("input").bind("keydown", function (event) {
    console.log(event.type, event);
});

As for Latin alphabet there was no problem and above code works well, but in case of Japanese/Chinese characters it didn’t. Keydown event didn’t occured at all when user write some text in Japanese. Fortunately, the problem can be solved quickly with following code:

$("input").bind("keydown input", function (event) {
    console.log(event.type, event);
});

In case of Japanese/Chinese characters we need to listen always to two type of events: keydown and input.

Complete list of events

  • keydown – occurs when key is pressed
  • keypress – represents a character being typed
  • keyup – after key is released
  • input – fired after input field is changed
  • paste – after user paste content into field

Brief explanation about key events can be found here.

Best auto-completion/tagging plugin

As there is no need to reinvent the wheel, I found very good jQuery tagging and auto-completion plugin called Select2. This plugin replaces input box and drop down lists, allowing user to add tags, with instant wordauto-completion. Plugin was created by Ivay Berg. This plugin also have the same problem with Japanese characters, but it can be easily fixed using code above.