LoginSignup
9
7

More than 5 years have passed since last update.

[JQuery] カーソルキーの↑↓でinputのフォーカスを移動させる

Last updated at Posted at 2017-12-25

Qiitaの新着記事を眺めていたら
 jQuery JavaScript 「↓」、「↑」キーでinputのフォーカスを移動させる
という記事を見かけまして。

ああ、そういえば昔同じことやったな と記憶から引っ張り出してみました。
おそらくこちらのほうが先の記事よりもスマートな実現方法ではないかな、と思います。

やりたいこと

縦に並んだINPUTコントロールを、カーソルキーの↑↓で移動したい。

前提条件

  • JQuery使用。
  • カーソルでフォーカス移動したいコントロールは、同じクラス名を持つこと。
    それ用にクラスを設定すればいいだけなので、使えない状況は無いはず。

ソース

html
<INPUT type="text" class="sample_class"><BR>
<INPUT type="text" class="sample_class"><BR>
<INPUT type="text" class="sample_class"><BR>
<INPUT type="text" class="sample_class"><BR>
<INPUT type="text" class="sample_class"><BR>
javascript
$(document).on("keydown", ".sample_class", function(e){

    var index       =   null;
    var selector    =   ".sample_class";

    //  ↑キー
    if ( e.keyCode == 38 ){
        index   =   $(selector).index(this);
        if (index > 0){
            $(selector).eq(index-1).focus();
        }
        return;
    }
    //  ↓キー
    if ( e.keyCode == 40 ){
        index   =   $(selector).index(this);
        if (index < $(selector).length - 1 ){
            $(selector).eq(index+1).focus();
        }
        return;
    }
});

簡単に解説

  • キーDownイベント。
  • イベントが発生したコントロールの index を取得。
  • 押されたカーソルキーによって index に -1 or + 1 し、 そのindexのコントロールを指定して focus() する。
  • index が境界外に出ないように条件をつける。
9
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
7