input イベント
【開発環境】
OS:Win11(64ビット)
VSCode1.72.2、
クロム
【inputイベントの使い方】
input イベントはフォーム( input 要素)や選択メニュー( select 要素 )、テキストエリア( textarea 要素)にてユーザーの操作によって値が変更されたときに発生するイベントです。 HTMLElement オブジェクトで発生します。
【要素属性:oninputにイベントハンドラーを登録した場合】
<label>名前:
<input type="text" oninput="inputChange()">
</label>
<script>
function inputChange(){
console.log('Change');
}
</script>
【oninput プロパティにイベントハンドラーを登録した場合】
<label>名前:
<input type="text" id="nametext">
</label>
<script> function inputChange(){
console.log('Change');
}
let text = document.getElementById('nametext');
text.oninput = inputChange;
</script>
【イベントリスナーを登録】
<label>名前:
<input type="text" id="nametext">
</label>
<script>
function inputChange(){
console.log('Change');
}
let text = document.getElementById('nametext'); text.addEventListener('input', inputChange);
</script>
【引数:Eventが渡された場合】
要素に対してプロパティへイベントハンドラを登録した場合と、 addEventListener メソッドを使ってイベントリスナーを登録した場合、イベントが発生してイベントハンドラやイベントリスナーが呼び出されるとき、引数として発生したイベントに関する情報が含まれる Event オブジェクトが渡されてきます
<label>名前:
<input type="text" id="nametext">
</label>
<script>
function inputChange(event){
console.log(event);
}
let text = document.getElementById('nametext');
text.addEventListener('input', inputChange);
</script>
サンプル
「input.js」のコード
ブラウザを立ち上げる

名前を入力

【InputEventオブジェクトで取得できる入力された文字の値】
input イベントが発生しイベントハンドラやイベントリスナーが呼び出されるとき、引数として発生したイベントに関する情報が含まれる InputEvent オブジェクトが渡されてきます。 InputEvent オブジェクトにはイベントが発生した時に押されたキー情報が含まれています。

ブラウザを立ち上げて、入力する

※コメント投稿者のブログIDはブログ作成者のみに通知されます