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()
関連記事
-
-
jQuery UIのDatepickerでリセット(入力内容消去)ボタンの追加方法
jQuery UIのDatepickerでキーボード入力を防ぎたいためreado ...
-
-
jquery.cookie.jsで保存期間を時間指定する方法
jquery.cookie.jsで保存期間を1時間等、時間指定したい。公式サイト ...
-
-
FormDataを使ったAjax通信がiPhoneのみエラー
FormDataオブジェクトを使用したAjax通信するシステムがあり、PCやAn ...
-
-
フォームの入力内容をjQueryで取得し、本文として設定した上でメーラーを起動させる方法
formで何らかを入力してもらいボタンをクリックするとメーラーが開き、先ほど入力 ...
-
-
PHPとajaxでチャットの作成
■ソース ・index.php <? error_reporting(E_ ...