12
8

More than 5 years have passed since last update.

Enterキーでonclickと同じ動作を行う。

Last updated at Posted at 2019-06-02

HTMLのformのテキスト(<input type="text">)などは入力し、エンターを押したとき、submitが押されたのと同じ状態になり、ページがリロードされてしまいます。そこでエンターを押したときにbuttonのonclickを押したときと同じ状態にできるようにする方法をメモします。

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>Sample</title>
    <script>
        function abc(){
            document.getElementById("a").textContent = "";
            return false;
        }
    </script>
</head>
<body>
    <form onsubmit="return abc()">
        <input type="text">
    </form>
    <div id="a"></div>
</body>
</html>

form要素の開始タグに「onsubmit="return abc()"」のようにイベントハンドラを追加し、関数abc()にreturn falseを指定することでフォームが送信されず、ページが再読み込みされなくなります。よって「あ」という文字をdiv要素に書き込めます。

このページを参考にしました。
https://www.tagindex.com/javascript/form/submit.html

12
8
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
12
8