2
4

More than 1 year has passed since last update.

Javascriptでinputのテキスト変更後に処理

Last updated at Posted at 2021-10-03

過去に書いたウィンドウリサイズのパロディ
オートコンプリートとかでつかえるかもな、、と勝手に思っています

入力項目のHTML
<input type="text" id="test">
// 変更が止まった後、指定時間(ミリ秒)後処理を行う
const term = 500;
// タイマーの受取変数
let timer = 0;
// 変更時に処理した内容を退避
let testValue = "";

window.addEventListener("load", function () {

    const testText = document.getElementById("test");
    // テキストに入力されているときの処理
    testText.addEventListener("input", function () {
        // 内容が変わっているときは、タイマーをリセットする
        clearTimeout(timer);

        // 指定時間後、一度だけ処理を実行
        timer = setTimeout(function () {
            // 内容が同じ場合は処理しない(エンターの決定対策)
            if (testValue !== testText.value) {
                // 処理時のテキスト内容を保持
                testValue = testText.value
                // 実際の処理を記載↓↓
                console.log(testText.value)
            }
        }, term);
    });
});

最近、Reactとかvueとかも経験値がたまってきたので、そっちでの記述も考えたい。

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