1. ホーム
  2. javascript

[解決済み] jQueryを使わずにプログラムで "input "イベントを発生させるには?

2023-01-18 22:59:23

質問

イベントハンドラを input を使って

var element = document.getElementById('some-input');
element.addEventListener('input', function() {
    console.log('The value is now ' + element.value);
});

予想通り、テキストフィールドに入力するとハンドラが起動しますが、私のコードからこのハンドラを呼び出す必要もあります。どのようにすれば input イベントをシミュレートして、私のイベントリスナーを呼び出すにはどうしたらよいでしょうか?

どのように解決するのですか?

JavaScriptでイベントを発生させるには、Eventオブジェクトを作成し、それをディスパッチします。

var event = new Event('input', {
    bubbles: true,
    cancelable: true,
});
  
element.dispatchEvent(event);

あるいは、シンプルなワンライナーとして

element.dispatchEvent(new Event('input', {bubbles:true}));

フィドル

これはIEではサポートされていませんので、昔ながらの方法を使用する必要があります。

var event = document.createEvent('Event');
event.initEvent('input', true, true);

elem.dispatchEvent(event);