2011-01-13 4 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

내가 그 상황에서 사용하는 코드의 조각, 수표의 경우 HTML5 자리 [http://dev.w3.org/html5/spec/Overview.html#the-placeholder-attribute]하지 그가

  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')); 
        } 
       }); 
      } 

그래서 그냥 같이 당신의 요소 쓰기를 제공하는 경우 지원, avaible이다 : <input name="foo" type=text" placeholder="Placeholder text" />

관련 문제