LoginSignup
0
0

More than 1 year has passed since last update.

イベント

Last updated at Posted at 2022-12-15

イベント

リンクやボタンをクリックしたり、キーボードを操作したり、また、ページの読み込みが完了した時にや次のページに行く直前など様々なタイミングでブラウザにイベントが発生します。

<section>
  <form action="#" id="form">
    <input type="submit" value="検索">
  </form>
</section>
<script>
    'use strict';

    document.getElementById('frm').onsubmit = function() {
        console.log('クリックされました');
    };
</script>

.onsubmit

  • JavaScriptのonsubmitとは、送信ボタンが押された時に起動するイベントです。

出典

document.getElementById('frm').onsubmit = function() {
        console.log('クリックされました');
    };

onsubmitイベントが発生した時に実行させたい処理を書きます。
この場合はコンソールオブジェクトに文字列が出力させる処理が書かれている。

フォームの入力内容を読み取る

<section>
  <form action="#" id="form">
    <input type="text" name="word">
    <input type="submit" value="検索">
  </form>
  <p id="output"></p>
</section>

<script>
    'use strict';

    document.getElementById('form').onsubmit = function() {
        event.preventDefault();
        const search = document.getElementById('form').word.value;
        document.getElementById('output').textContent = `「${search}」の検索中...`;
    };
</script>

idがformの値の属性値を取得する

const search = document.getElementById('form').word.value;

idがformのオブジェクトを取り出して、word(name属性)の値を定数に代入している。

document.getElementById('output').textContent = `「${search}」の検索中...`;

idのoutputのノード内のテキストに上書きする

関連

イベントから先に行かない

event.preventDefault();

インターフェイスのpreventDefault()メソッドは、イベントが明示的に処理されない場合、通常のようにデフォルト アクションを実行しないことをユーザー エージェントに伝えます。Event

出典

感想

まだjavascriptに慣れないとダメだな。

出典

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