jQuery onメソッドを使ってテキストボックスに複数のイベントリスナを登録する
環境
Windows 10 home 64bit
jQuery 3.6.1
書式
$(“セレクター名").on({
“focus".function(e){カーソルを当てる処理コード}
“blur".function(e){カーソルを外す処理コード}
“change":function(e){変更でエンターキーを押す処理コード}
})
使用例
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".username").on({
"focus":function(e){
$("#res").text("focusいイベント");
},
"blur":function(e){
$("#res").text("blurイベント");
},
"change":function(e){
$("#res").text("changeイベント");
}
});
});
</script>
</head>
<body>
名前:<input type="text" class="username" value="山田" maxlength="6">
<p>イベント名:<span id="res"></span></p>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".username").on({
"focus":function(e){
$("#res").text("focusいイベント");
},
"blur":function(e){
$("#res").text("blurイベント");
},
"change":function(e){
$("#res").text("changeイベント");
}
});
});
</script>
</head>
<body>
名前:<input type="text" class="username" value="山田" maxlength="6">
<p>イベント名:<span id="res"></span></p>
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script> $(document).ready(function(){ $(".username").on({ "focus":function(e){ $("#res").text("focusいイベント"); }, "blur":function(e){ $("#res").text("blurイベント"); }, "change":function(e){ $("#res").text("changeイベント"); } }); }); </script> </head> <body> 名前:<input type="text" class="username" value="山田" maxlength="6"> <p>イベント名:<span id="res"></span></p> </body> </html>
実行結果
テキストボックス内にカーソルを当てる場合、「focusいイベント」が表示されます。
カーソルを外して任意の箇所をクリックする場合、「blurイベント」が表示されます。
値を変更してテキストボックス内でエンターキーを押す場合、「changeイベント」が表示されます。