simonyoung
simonyoung

Reputation: 855

Is there a more efficient/optimized way to write this piece of jQuery?

What is the most efficient way of coding the below functions which warn people if they try to submit an empty form and also clear forms for them to enter?

$("#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;
     }

    });

Upvotes: 0

Views: 69

Answers (3)

Hannes
Hannes

Reputation: 8237

heres a Piece of Code i use in that Situation, checks if HTML5 placeholder [ http://dev.w3.org/html5/spec/Overview.html#the-placeholder-attribute ]Support is avaible, if not he provides it

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

so just write your elements like: <input name="foo" type=text" placeholder="Placeholder text" />

Upvotes: 1

Ivan
Ivan

Reputation: 3645

There most probably is the way of doing this more efficiently. However your code is quite alright. There is no loops no massive data structures. There shouldn't be a reason to spend time optimizing this.

Upvotes: 0

Oded
Oded

Reputation: 498972

You may want to look at the jQuery Watermark plugin.

This plugins let's you add default text on form elements that look like watermarks or work as placeholders ... work in a way to prevent unwanted information to be sent to the server

Upvotes: 3

Related Questions