9
7

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 5 years have passed since last update.

RailsのフォームでEnterキーを押したときのsubmitを防ぐ術

Posted at

はじめに

フォームでEnterキーを押すと、submitされてしまう。
本来であれば、キーボード操作だけで処理が完結し、便利だと感じるが、逆に「まだ送信したくなかったのに...!」と感じるときもある。
今回はEnterキーでのsubmitを無効化し、該当するボタンをクリックしたときにだけ、submitが実行されるようにする方法を記す。

※Chromeでのみ検証しています

環境

  • Rails 5.2.1
  • テンプレートエンジン slim

やったこと

デフォルト
= form_with model: @user, url: users_path, method: :post, local: true do |f|
  = f.text_field :name
  = f.submit '送信する'

このときに通常であればsubmitの処理が走るので、代わりにbuttonを使う。

buttonバージョン
= form_with model: @user, url: users_path, method: :post, local: true do |f|
  = f.text_field :name
  = f.button '送信する', type: 'button', onclick: 'submit();' # typeとonclickを追加

buttonにすることで、Enterでのsubmitが発生しないようになり、onclickを付与することでボタンクリック時に送信されるようになる。

ちなみに

生のHTMLで記述を加える場合は、下記の記事も参考になる。
Enterキーを無効にする方法

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?