0
2

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.

input, textareaの初期値の色を変えて表示し、フォーカスでvalueを削除する。

Last updated at Posted at 2015-08-06

やりたいこと

  • input タグのtextタイプに初期値を設定。
  • 文字は薄い色の文字で表示をしたい。
  • アクティブになると文字が消え、通常の黒文字で入力できる。
  • フォーカスを解除すると、文字がなければ、デフォルト値を表示し、文字入力があれば、入力値をそのまま表示する。

設定

htmlのサンプル

<input type="text" name="keyword" id="keyword" value="hoge" />

javascriptのサンプル

$(document).ready(function(){
  var def_css   = {color : '#999999'};
  var focus_css = {color : '#000000'};
  var selector  = $('#keyword');

  //初期の色セット
  selector.css(def_css);

  //フォーカス時の色と値の変更
  selector.focus(function(){
    if($(this).val() == this.defaultValue){
      $(this).val('');
      $(this).css(focus_css);
    }
  })
  //フォーカス解除時の色と値の変更
  selector.blur(function(){
    if($(this).val() == this.defaultValue || $(this).val() == ''){
      $(this).val(this.defaultValue);
      $(this).css(def_css);
    };
  });
});

余談

実は、スクリプトを書かなくても、HTML5なら placeholder 属性を指定すると簡単にできる。

<input type="text" name="keyword" id="keyword" placeholder="hoge" />
0
2
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
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?