0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【jQuery】form内でEnterキーを押すと次の要素にフォーカスさせる

Last updated at Posted at 2021-11-04

ささっと作ってみた。

.js
$('form input, form select').on("keypress", function (e) {
    if (e.key === "Enter") {
        let submit = false;
        let reverse = false;
        let nowinput = this;
        let inputs = $(this).closest('form').find('input:visible:not(input[readonly]), select:visible:not(input[readonly])');
        if (e.shiftKey) {
            reverse = true;
            inputs = $($(inputs).get().reverse());
        }
        inputs.each(function (index, input) {
            if (nowinput == input) {
                if (index < inputs.length - 1) {
                    $(inputs[index + 1]).focus();
                    return false;
                } else {
                    submit = true;
                    return false;
                }
            }
        });
        if (submit && !reverse) {
            return true;
        } else {
            return false;
        }
    }
});

動作としては以下の通り。

  • フォーム内でEnterキーを押すと次の要素(input,select)にフォーカス
  • 次の要素がなかった場合はそのまま送信
  • 非表示またはreadonlyになっているinputはフォーカス対象にならない
  • Shiftキーを押しながらEnterキーを押すと逆順にフォーカス

留意点とか

  • textareaに対応させてない
  • 気が向いたら対応させます
  • Ctrl+Enterで一発送信させたいかも
  • こちらも気が向けば対応
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?