JavaScript / jQueryにてページ表示時に指定したテキストボックスにフォーカスさせる方法
ページを開いた際に指定したテキストボックス(input type="text")にフォーカスさせてほしいという要望を受けた。JavaScript及びjQueryでの対応方法をメモ。
対応方法
ソースコード
<input type="text" id="test">
<script type="text/javascript" src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
//JavaScriptの場合
document.querySelector(`#test`).focus();
$(function(){
//jQueryの場合
$(`#test`).focus();
});
</script>
リファレンス
HTMLElement: focus() メソッド
https://developer.mozilla.org/ja/docs/Web/API/HTMLElement/focus
.focus()
関連記事
-
-
FormDataを使ったAjax通信がiPhoneのみエラー
FormDataオブジェクトを使用したAjax通信するシステムがあり、PCやAn ...
-
-
jQueryとCSSで指定したテキストに対してラインマーカーを引く方法
サイト内で強調したいテキストに対して蛍光ペンでマーカーを引くようなアニメーション ...
-
-
jQueryのfind実行時に複数のセレクタを指定する方法
jQueryのfind()実行時に複数のセレクタを指定したい。 <div ...
-
-
jquery.cookie.jsで保存期間を時間指定する方法
jquery.cookie.jsで保存期間を1時間等、時間指定したい。公式サイト ...
-
-
「input type="number"」のテキストボックスを桁数制限且つ半角数値のみ入力可にする方法
「input type="number"」のテキストボックスに対して「2桁まで」 ...