勉強したことのメモ

Webエンジニア / プログラマが勉強したことのメモ。

JavaScript / jQueryにてページ表示時に指定したテキストボックスにフォーカスさせる方法

  jQuery JavaScript

ページを開いた際に指定したテキストボックス(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()

https://api.jquery.com/focus-shorthand/

 - jQuery JavaScript

  関連記事

jQueryで要素を移動する方法のまとめ

jQueryで要素を移動する際、insertBefore / insertAft ...

jQueryでAjax通信したデータをPHPで受け取り、zip化したファイルをダウンロードさせる方法

jQueryのAjaxで何らかのデータをPHP側に送信し、PHP側で当該データを ...

jQselectableでセレクトボックスをリッチにする

入力フォームみたいなもので元々はテキストボックス内に 都道府県を入れてもらうとい ...

jquery.cookie.jsで「$.cookie is not a function」エラー

フロントエンド側でCookieを利用したい場合jquery-cookieを用いる ...

jQuery UIのDatepickerでリセット(入力内容消去)ボタンの追加方法

jQuery UIのDatepickerでキーボード入力を防ぎたいためreado ...