勉強したことのメモ

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でshow/hideよりaddClass/removeClassの方が速い

diaplay:none/blockする際に最近はshow()/hide()を ...

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

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

Lightboxで画像拡大時に閉じるボタンの位置を右上に変更

Lightbox(バージョン2.7.1)で画像拡大時に閉じるボタンの位置を右下か ...

jquery.cookie.jsで保存期間を時間指定する方法

jquery.cookie.jsで保存期間を1時間等、時間指定したい。公式サイト ...

FullCalendarでカレンダー内のイベントをクリックした際にタイトル以外の内容も表示させる方法

FullCalendarでカレンダー内のイベントをクリックした際にtitle以外 ...