2011-01-22 1 views
7

私は電子メールフォームのテキストボックスを持っています。空の状態で「電子メール」という値を持っていて、それをクリックするとテキストが消えてしまいます。誰かがそれをクリックしてテキストを入力しなかった場合。ぼかしではデフォルトのテキストに戻ることができます。JQuery空のテキストボックスの既定のテキスト

私はいくつかのことを試みてきましたが、何も機能していません。誰かが正しい方向に私を指差してくれますか?

答えて

3

It's pretty straightforward.onfocusの値を消去してから(値がまだ空の場合)、onblurを埋め込みます。

+0

この例では、入力フィールドで新しく入力したテキストも削除します。これは必要ではありません。 – webtweakers

1

次の関数を呼び出し、2つの引数を渡します:slightLabel(jQuery( '#email_field')、 'email');

function slightLabel(input, text) { 
     jQuery(input).val(text); 
     jQuery(input).data('defaultText', text); 
     jQuery(input).focus(function(){ 
      if(!jQuery(this).data('touched')) 
      { 
       jQuery(this).data('touched', true); 
       jQuery(input).val(''); 
      } 
     }); 

     // the part to restore the original text in 
     jQuery(input).blur(function(){ 
      if(jQuery(this).val() == '') 
      { 
       jQuery(this).val(jQuery(this).data('defaultText')); 
      } 
     }); 

    } 
1

ちょうどそれを行うjqueryの透かしプラグインの1つを使用できます。私は次のコードを持つ透かしプラグインを使用します。

$.fn.watermark = function (c, t) { 
var e = function (e) { 
    var i = $(this); 
    if (!i.val()) { 
     var w = t || i.attr('title'), $c = $($("<div />").append(i.clone()).html().replace(/type=\"?password\"?/, 'type="text"')).val(w).addClass(c); 
     i.replaceWith($c); 
     $c.focus(function() { 
      $c.replaceWith(i); setTimeout(function() { i.focus(); }, 1); 
     }) 
      .change(function (e) { 
       i.val($c.val()); $c.val(w); i.val() && $c.replaceWith(i); 
      }) 
      .closest('form').submit(function() { 
       $c.replaceWith(i); 
      }); 
    } 
}; 
return $(this).live('blur change', e).change(); 

};

この

<input type="text" id="keyword" name="keyword" class="watermark" style="width: 250px" 
    title="Type keyword here" /> 

のようなタイトルを透かし入力テキストボックスのクラスを設定することにより、jqueryので呼び出し可能なウォーターマークで表示されるものです。

9

それがこの

$('#yourElement').focus(function(){ 
    //Check val for email 
    if($(this).val() == 'E-Mail'){ 
     $(this).val(''); 
    } 
}).blur(function(){ 
    //check for empty input 
    if($(this).val() == ''){ 
     $(this).val('E-Mail'); 
    } 
}); 
+0

これは最初の行でのみ動作しますなぜそれはそうですか? – DharaPPatel

20

それとも、単にプレースホルダーHTML5の属性を使用することができますような何か行く:

<input type="text" id="keyword" name="keyword" placeholder="Type keyword here" /> 
+0

プレースホルダ属性について知らなかった。素晴らしい追加! :)現時点ではIEがサポートしていないのは残念です(IE 9)。 –

+16

IEはまだWebブラウザであると考えていますか? – webtweakers

5

あなたがIE

のバックアップとして、このjqueryのをプレースホルダー属性を使用して、私たちすることができますが
<input type="text" id="keyword" name="keyword" placeholder="The watermark" value='The watermark' class="watermark"/> 

$(document).ready(function() { 
    $('.watermark').focus(function() { 
     if ($(this).val() == $(this).attr('placeholder')) { 
      $(this).val(''); 
     } 
    }).blur(function() { 
     if ($(this).val() == '') { 
      $(this).val($(this).attr('placeholder')); 
     } 
    }); 
}); 
1

これを使用するJquery-placeholderプラグイン

このプラグインを使用すると、HTML5対応ではないブラウザでもプレースホルダ属性を使用できます。

関連する問題