Help us understand the problem. What is going on with this article?

かな入力モードで入力できない文字をJavaScriptでなんとかする方法

More than 5 years have passed since last update.

経緯

かな入力中によく使う記号入力させてくれ的な謎の要望が来て対応したときのメモ。
環境はInternetExplorerで、かつMS-IME使っている場合限定。GoogleIMEとか使ってると動かない。

コード

var charTable = {
    '' : '@',
    '' : '=',
    '' : '*'
};
$("input[type=text],textarea").on("keydown", function(e){
    var converted = charTable[e.char];
    if (e.keyCode === 229 && e.shiftKey && converted) {
        e.key = e.char = converted;
        this.value += converted;
        e.preventDefault();
    }
});

日本語入力中のキーイベント

keydownとkeyupが発生する。keypressは発生しない。

event.keyCodeは入力キーの場合、常に229。

ローマ字入力、かな入力の判定は、event.char または event.keyで行う(どっちも同じのが入ってるっぽい)。
MS-IMEを使っていると、event.charにローマ字入力の場合は半角英数字、かな入力の場合は半角カナが入っていて、それで判定してる。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away