LoginSignup
28
27

More than 1 year has passed since last update.

オートフォーカスしてカーソルを末尾に移動させる小技

Last updated at Posted at 2013-10-14

【2021/10/15 追記】
この記事は更新が停止されています。現在ではブラウザの動作が変化している面もありますので,過去の記事として参考程度にご覧ください。

HTML5の autofocus 属性を使うとChrome以外でうまく動作しないので別の方法を採用しました。
jQueryを使ったほうが短く書けますが、ここでは使わずに書いてみます。

PHP
$val = isset($_GET['val']) && is_string($_GET['val']) ? $_GET['val'] : '';
$val = htmlspecialchars($val, ENT_QUOTES, 'UTF-8');
JavaScript
function load_focus() {
  var elm = document.test_form.test_text;
  var val = elm.value;
  elm.value = '';
  elm.focus();
  elm.value = val;
}
HTML
<body onload="load_focus()">
<form name="test_form" method="get" action="">
<label>TestText: <input type="text" name="test_text" value="<?=val?>"></label>
<label><input type="submit" value="送信"></label>
</form>
</body>
  • 入力済みのvalueがある場合は一度空にする
  • フォーカスしてから値をセットする

この2点を守るのがポイントです。
これで

  • Internet Explorer
  • Mozilla Firefox
  • Google Chrome

3ブラウザとも動作確認できました。

28
27
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
28
27