5
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.

[jQuery]フォームの透かし文字をtitleやvalueを使わず設定する

Last updated at Posted at 2015-02-22

フォームのインプット欄に透かし文字を入れるのにvalueやtitle属性を使うプラグインは多いのですが、それだと不都合な場合は以下のコードで対応しています。

今回、HTML5のplaceholeder属性は無視しています。

※入力欄に入力した状態で送信→ブラウザの戻る機能で戻った時は、透かし文字が消えず文字がかぶってしまう状態ですので、戻る可能性がある際はご注意ください。
ページ戻りに対応しました。

jQuery

$(function() {
	var wmText = ".watermark_text";	//透かし文字(テキスト)
	var wmCell = ".watermark";		//透かし文字を入れる入力欄(inputやtextareaなど)

	// 透かし文字をクリックした際の処理
	$(wmText).click(function(){
		$(this).addClass("hidden");
		$(this).parent().children(wmCell).focus();
	});

	$(wmCell).each(function(){
		//テキストボックスの値が空でなければ透かし文字を非表示に
		if ($(this).val() !== '') {
			$(this).parent().children(wmText).addClass('hidden');
		}

		// テキストボックスをフォーカス・ブラーした際の処理
		$(this).focus(function(){
			var wmText_on = $(this).parent().children(wmText);
			$(wmText_on,this).addClass("hidden");
		}).blur(function(){
			var wmText_on = $(this).parent().children(wmText);
			if($(this).val()== ""){
				$(wmText_on,this).removeClass("hidden");
			};
		});

	});
});

HTML

<div>
	<span class="watermark_text">例)ここに透かしたい文字を入れます</span>
	<input class="watermark">
</div>

CSS

/* 親要素 */
div {
	position:relative;
}

/* 透かし文字 */
.watermark_text {
	position:absolute; 	/* これを入れないと入力欄にかぶりません */
	padding: 5px; 		/* 透かし文字を自然な位置に置くため適当なpaddingを入れます */
	color: #999; 		/* 透かし文字なので薄めの文字色がいいかもしれません。お好みで。 */
}

/* 透かし文字を非表示にするためのclass */
.hidden {
	visibility: hidden;
}
5
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
5
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?