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

form要素内のエンターキーによる意図しないボタン発火防止

Last updated at Posted at 2022-01-12

シチュエーション

form要素内にあるテキストボックスにカーソルを当てた状態でエンターキーを押すと、
form要素内のボタンが発火する。

<form>
    <input type="text" />
    <button onclick="hogeEvent()">hoge</button>
    <input type="submit" value="submit" />
</form>

上記の場合、hogeボタンが発火した。
hogeボタンをコメントアウトしてみたらsubmitボタンが発火した。

原因

HTMLの仕様がそうなっているから
https://developer.mozilla.org/ja/docs/Web/HTML/Element/form

対処

input要素はbutton要素にして、typeを button にする。
submitは onclick="submit();" を設定する。

<form>
    <input type="text" />
    <button type="button" onclick="hogeEvent()">hoge</button>
    <button type="button" onclick="submit();">submit</button>
</form>

これにより、form要素内のボタンの意図しない発火を防ぐことができる。

参考

Enterキーを無効にする方法
Enterキーを押すとsubmitされるのを防ぐ

1
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
1
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?