2011-01-13 9 views
0

以下の機能をコーディングする最も効率的な方法は何ですか?人々は空のフォームを提出しようとした場合、そのフォームをクリアして入力するよう警告しますか?jQueryのこの部分を書くために、より効率的に/最適化された方法がありますか?

$("#newsletter-subscribe").focus(function() { 
     if(this.value=='Your email address'){ 
      this.value=''; 
     } 
    }); 

    $("#newsletter-subscribe").blur(function(){ 
     if(this.value==''){ 
      this.value='Your email address' 
     }; 
    }); 

    $("#subscribe").bind("submit", function(e){ 
     email = $("input#newsletter-subscribe").val(); 
    $("input#newsletter-subscribe").val(email); 
    if(jQuery.trim(email) == 'Your email address' || jQuery.trim(email) == '') { 
     alert('Please enter your email address to subscribe.'); 
     return false; 
    } 

    }); 

答えて

3

jQuery Watermarkプラグインをご覧ください。

このプラグインは不要な情報を防止するための方法で仕事がおそらくあり、サーバ

+0

これは私が探していたものに完璧です - ありがとう! – simonyoung

0

に送信する...あなたはプレースホルダとして、透かしや仕事のように見えるフォーム要素のデフォルトのテキストを追加してみましょうこれをより効率的に行う方法です。しかし、あなたのコードはかなり大丈夫です。膨大なデータ構造のループはありません。これを最適化するために時間を費やす理由はないはずです。 HERESに

1

私はそのような状況で使用するコードの一部、小切手彼は

  if(!('placeholder' in document.createElement('input'))){ 
       $('input[type="text"][placeholder] , textarea[placeholder]').each(function(){ 
        if('' != $(this).attr('placeholder')){ 
         if('' == $(this).val() || $(this).attr('placeholder') == $(this).val()){ 
          $(this).val($(this).attr('placeholder')).css('color','gray'); 
         } 
        } 
       }); 
       $('input[type="text"][placeholder], textarea[placeholder]').focus(function(){ 
        if($(this).attr('placeholder') == $(this).val()){ 
         $(this).val(''); 
         $(this).css('color','#272727'); 
        } 
       }).blur(function(){ 
        if('' == $(this).val()){ 
         $(this).css('color','gray').val($(this).attr('placeholder')); 
        } 
       }); 
      } 

ので、同じようにあなたの要素を書き、それを提供しない場合はHTML5のプレースホルダは、[http://dev.w3.org/html5/spec/Overview.html#the-placeholder-attribute]サポートは、avaibleである場合: <input name="foo" type=text" placeholder="Placeholder text" />

関連する問題