Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear input on focus with jQuery and return on blur

Tags:

jquery

This almost works. However, when leaving the field "defaulttext" appears rather than the original text value. Not sure how to most efficiently echo the variable inside defaultText.

$(function() {
    var defaultText = $(this).val();
    $('input[type=text]').focus(function() {
      $(this).val('');
      });
     $('input[type=text]').blur(function() {
      $(this).val('defaultText');
      echo 
      });
 });
like image 456
cchiera Avatar asked Jan 26 '12 00:01

cchiera


1 Answers

$(function() {
    var input = $('input[type=text]');

    input.focus(function() {
         $(this).val('');
    }).blur(function() {
         var el = $(this);

         /* use the elements title attribute to store the 
            default text - or the new HTML5 standard of using
            the 'data-' prefix i.e.: data-default="some default" */
         if(el.val() == '')
             el.val(el.attr('title'));
    });
 });

Update

Browsers are progressively implementing the placeholder attribute, which provides the ability to display a "hint" to the user.

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input#attr-placeholder

like image 168
Alex Avatar answered Oct 19 '22 18:10

Alex