jQuery の実装を使用すると、送信時にデフォルト値を簡単に削除できます。以下に例を示します。
$('#submit').click(function(){
var text = this.attr('placeholder');
var inputvalue = this.val(); // you need to collect this anyways
if (text === inputvalue) inputvalue = "";
// $.ajax(... // do your ajax thing here
});
あなたがオーバーレイを探していることは知っていますが、このルートの簡単さを好むかもしれません (私が上に書いたことを知っています)。もしそうなら、私は自分のプロジェクトのためにこれを書きました。これは非常にうまく機能し (jQuery が必要です)、サイト全体に実装するのに数分しかかかりません。最初はグレーのテキストが表示され、フォーカスが合っているときはライトグレー、入力中は黒になります。また、入力フィールドが空の場合はいつでもプレースホルダー テキストを提供します。
最初にフォームを設定し、入力タグにプレースホルダー属性を含めます。
<input placeholder="enter your email here">
このコードをコピーして、placeholder.js として保存します。
(function( $ ){
$.fn.placeHolder = function() {
var input = this;
var text = input.attr('placeholder'); // make sure you have your placeholder attributes completed for each input field
if (text) input.val(text).css({ color:'grey' });
input.focus(function(){
if (input.val() === text) input.css({ color:'lightGrey' }).selectRange(0,0).one('keydown', function(){
input.val("").css({ color:'black' });
});
});
input.blur(function(){
if (input.val() == "" || input.val() === text) input.val(text).css({ color:'grey' });
});
input.keyup(function(){
if (input.val() == "") input.val(text).css({ color:'lightGrey' }).selectRange(0,0).one('keydown', function(){
input.val("").css({ color:'black' });
});
});
input.mouseup(function(){
if (input.val() === text) input.selectRange(0,0);
});
};
$.fn.selectRange = function(start, end) {
return this.each(function() {
if (this.setSelectionRange) { this.setSelectionRange(start, end);
} else if (this.createTextRange) {
var range = this.createTextRange();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', start);
range.select();
}
});
};
})( jQuery );
1 つの入力だけで使用するには
$('#myinput').placeHolder(); // just one
これは、ブラウザーが HTML5 プレースホルダー属性をサポートしていない場合に、サイトのすべての入力フィールドに実装することをお勧めする方法です。
var placeholder = 'placeholder' in document.createElement('input');
if (!placeholder) {
$.getScript("../js/placeholder.js", function() {
$(":input").each(function(){ // this will work for all input fields
$(this).placeHolder();
});
});
}