1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

テキストエリアをフォーカスしたときに全選択状態にする

Last updated at Posted at 2017-03-24

はじめに

以下のような使われ方のテキストエリアは、
フォーカスした瞬間に全選択にしてしまいましょう

  • コピーさせたい
  • 基本上書きする

前者は、生成されたURLやテキストを貼り付けるフォームなど
後者は、入力フォームなど

方法

テキストエリアをフォーカスしたときに全選択状態にする①
$(document).ready(function(){
    $('#text').focus(function(){
        $(this).select();
    });
});

HTML内の<input type="text">全てにこの設定が適用されます

テキストエリアをフォーカスしたときに全選択状態にする②
$(document).ready(function(){
    $('#text2')
        .focus(function(){
          $(this).select();
      })
      .click(function(){
          $(this).select();
          return false;
      });
}); 

こちらは、フォーカスだけでなく、
clickイベントでも全選択状態になるような仕様です
テキストエリア内でクリックを繰り返すと、全選択と選択解除を繰り返します

さいごに

この仕様を実装したいと思ったのは、
IE10以降で実装された、input要素の「×」ボタンについて考えたときでした。

ブラウザによってついてたりついてなかったりすると、なんか不便。
でも、全消しするとき×ボタンがないとないで不便。
同じ手間で消せるor上書きできるようにしたいと考えて辿りついたのがこれです。

フォーカスした瞬間に全選択してしまえば、
BackSpaceで消せるしすぐに上書きもできるので便利!
途中に文字を挿入したいときには不便ですけどね。

参考

Javascriptで実装したい人向け

1
4
0

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
1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?