LoginSignup
2
1

More than 3 years have passed since last update.

【JavaScript】submitイベント

Last updated at Posted at 2020-11-08

プログラミング勉強日記

2020年11月8日
submitイベントについて、短くまとめる。

submitイベントとは

ユーザーが<input type='submit'>や<button>をクリックしたり、
フィールド内でenterを押すと、イベントが発生する。

submitイベントの書き方

index.html
  <form action="#" id="form">
        <input type="submit" value="検索" id="input">
    </form>
script.js

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

form要素のid属性を取得して、submitイベントが発生したら、コンソールにクリックされましたと文字列を表示する。

注意点

input要素のid属性やbutton要素を取得しても、submitイベントは発生しない。
submitイベントはform要素自身で発生するもの。

script.js

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

twitterにinput要素のid属性を取得した場合の挙動をツイート

formの入力内容を読み取る

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


//form要素のid属性を取得し、変数formに代入
let from = document.getElementById('form');

//p要素のid属性を取得し、変数outputに代入
let output =document.getElementById('output');

//取得したform要素内の送信ボタンがクリックされた時に発生
form.onsubmit = function (event) {

//form要素の基本動作をキャンセル
event.preventDefault();

//テキストフィールドの入力内容が定数searchに代入
const search = form.word.value;

//取得したp要素のコンテンツを『${search}』の検索中...に書き換える
output.textContent = `『${search}』の検索中...`;
}

参考資料

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