🕌

【JavaScript】フォーム部品へのアクセス

に公開3

フォーム部品へのアクセスは、textContentではなく、valueを使う

document.querySelector('button').addEventLister('click', () => {
    alert(document.querySelector('input').value);
    alert(document.querySelector('textarea').value);
    document.querySelector('textarea').value = ''; // 空文字でテキストクリア

    alert(document.querySelector('select').value); // ドロップダウンリストで選択した値を表示

    // ラジオボタンの場合は、反復処理でtrueをチェックして返す
    document.querySelectorAll('input').forEach((radio) => {
        if (radio.checked === true) {
            alert(radio.value);
        }
    });

    // チェックボックスの場合は、複数ある場合を想定してチェックをまとめる
    const arr = []; // チェックした答えをまとめるための配列
    document.querySelectorAll('input').forEach((checkbox) => {
        if (checkbox.checked === true) {
            arr.push(checkbox.value); // チェックした要素を配列に追加
        }
    });
    alert(arr.join(',')); // 配列でまとめないで、if文内のアラートだと複数表示される
});

clickではなく、値を取得するinput、changeイベント

  • text, textarea, select要素は、inputを使用
  • radio, checkbox要素は、changeを使用
document.querySelector('input').addEventListener('input', () => { // inputで値を取得
    const pElement = document.querySelector('p');
    const inputElement = document.querySelector('input');
    pElement.textContent = inputElement.value; // 値をpに反映

    pElement.textContent = inputElement.value.length; // 値の文字数をpに反映
});

フォーカス時のfocus、blueイベント

// focusでフォーカスした際にpを表示
document.querySelector('input').addEventListener('focus', () => {
    document.querySelector('p').textContent = '入力補足を表示';
});

// blueでフォーカスオフした際にpの空文字を表示
document.querySelector('input').addEventListener('blur', () => {
    document.querySelector('p').textContent = '';
});

// 初期値(画面表示時)をフォーカスにする命令
document.querySelector('input').focus();

キーダウンを取得するイベント

// ページ全体にイベント追加したいときは、querySelector()を省略する
document.addEventListener('keydown', (e) => {
    document.querySelector('p').textContent = e.key; // 入力されたキーを取得できる
});

マウス移動を取得するイベント

document.addEventListener('mousemove', (e) => {
    document.querySelector('p').textContent = `X: ${e.clientX} Y: ${e.clientY}`; // マウスの座標を取得できる
});

submitイベントを取得

  • formタグ要素内のbuttonをクリックすると、submitが発生する
  • submitすると別ページに遷移することを想定していて、該当ページを指定しなかった場合、リロードされる
document.querySelector('form').addEventListener('submit', (e) => {
    e.preventDefault(); // 遷移先ページを指定しない場合のリロード、という初期値の動きを防ぐ命令。
    document.querySelector('p').textContent = document.querySelector('input').value;
});

Discussion

junerjuner

どのボタンを押したかわかる SubmitEvent.prototype.submitter とかもあるとよいかも?

https://developer.mozilla.org/ja/docs/Web/API/SubmitEvent/submitter

nishimotonishimoto

ありがとうございます!ドキュメントで学習しました。
下記のように追加したいと思うのですが、もっと適した用例等あればご指摘お願いします。

複数のsubmitイベントを判別

  • 「保存して戻る」と「保存して次の入力に進む」などの分岐もできる
document.querySelector('.form').addEventListener('submit', (e) => {
    const submitter = e.submitter; // submitterで複数のsubmitを取得
    const handler = submitter.id; // submitのidを取得

    document.querySelector('p').textContent = document.querySelector('input').value;

    if (handler) {
        processOrder(form, handler); // processOrder() 関数を呼び出して、フォームとIDを渡す
    } else {
        ... 不明な処理などが行われた場合の記述
    }
});
<form>
    <input type="text">
    <button type="submit" id="search">保存して戻る</button>
    <button type="submit" id="download">保存して次の入力に進む</button>
</form>
junerjuner

submitter は 押したボタンなので 複数はないですね。
動かしてみたらわかると思いますが。

例はそんな感じでいいと思います。