テキストフィールド (html フォーム) をクリックして何かを書いた場合、テキストフィールド (html フォーム) を空にする方法を教えてください。
疑似コード:
On click #searchform
Erase String in #searchform
テキストフィールド (html フォーム) をクリックして何かを書いた場合、テキストフィールド (html フォーム) を空にする方法を教えてください。
疑似コード:
On click #searchform
Erase String in #searchform
$('#searchform').click(function() { $(this).val('') })
$('#searchform').click(function() {
if ($(this).val() == 'Enter search term') {
$(this).data('original', $(this).val()).val('');
}
});
$('#searchform').blur(function() {
if ($(this).val() == '') {
$(this).val($(this).data('original'));
}
});
編集今のところ、プレースホルダー属性を使用する必要があります。必要に応じて、プレースホルダーのサポートが欠落している場合のポリフィルとして上記を使用してください。
if (!('placeholder' in document.createElement('input'))){
$('input[placeholder]').each(function() {
$(this).placeholder();
});
}
元のコードをプラグインに変換して、簡単に使用できるようにします (いくつかの小さな変更を加えて)。
jQuery.fn.placeholder = function() {
return this.each(function() {
var value = $(this).attr('placeholder');
jQuery(this).val(value).addClass('placeholder');
jQuery(this).focus(function() {
if (jQuery(this).val() == value) {
jQuery(this).val('').removeClass('placeholder');
}
});
jQuery(this).blur(function() {
if (jQuery(this).val() == '') {
jQuery(this).val(value).addClass('placeholder');
}
});
});
};
HTML5 プレースホルダー属性を使用することをお勧めします。例えば:
<input type="text" placeholder="some default string if empty" />
これはほとんどの最新のブラウザーで動作し、古いブラウザーには回避策の jQuery プラグインがあります。プレースホルダー プラグインへのリンクは次のとおりです。
そして、次のように呼び出すだけです。
$('input[placeholder]').placeholder();
「Enter Search Term」などのフィールドからデフォルト値をクリアしたい場合は、次のコードを使用します。
function clearText(thefield){
if (thefield.defaultValue==thefield.value)
thefield.value = ""
}
次に、入力フィールドに次を追加します。
onfocus="clearText(this)"
したがって、次のようになります。
<input type="text" name="username" value="enter your name here" onfocus="clearText(this)">