2

I am using Jquery to remove a default value in an HTML input on focus.

However, if nothing is entered into the input I want the default value to re-appear.

To try and do this I have created:

$( "#contact input" ).each(function( index ) {

        $(this).focus(function() {
          var valvalue = $(this).val();
          $(this).val(''); 
        });

        $(this).focusout(function() {
            var newvalvalue = $(this).val();
            if(newvalvalue == ''){
              $(this).val('', valvalue); 
            }
        });

    });

The focus() function works fine, but the variable valvalue does not get picked up by the focusout function.

Would anyone know a way to pass the valvalue variable to that 2nd focusout function?

MeltingDog
  • 14,310
  • 43
  • 165
  • 295

3 Answers3

4

You need to make varvalue visble by both event handlers. It can be done by declaring it outside their scope.

$( "#contact input" ).each(function( index ) {

   var valvalue; /* both event handlers can see it here */

   $(this).focus(function() {
       valvalue = $(this).val();
       $(this).val(''); 
   });

   $(this).focusout(function() {
       var newvalvalue = $(this).val();
       if(newvalvalue == ''){
           $(this).val('', valvalue); 
       }
   });    

});
martynas
  • 12,120
  • 3
  • 55
  • 60
1

You're having an issue with closure scope in JS. Try defining varvalue outside your function so both functions reference the same variable.

$( "#contact input" ).each(function( index ) {
        var valvalue;
        $(this).focus(function() {
          valvalue = $(this).val();
          $(this).val(''); 
        });

        $(this).focusout(function() {
            var newvalvalue = $(this).val();
            if(newvalvalue == ''){
              $(this).val('', valvalue); 
            }
        });

    });
Tyler McGinnis
  • 34,836
  • 16
  • 72
  • 77
1

In addition to other answers, you can use placeholder property available in HTML5, if you don't want to support old browsers.

<input type="text" name="name" placeholder="Enter here">
Diode
  • 24,570
  • 8
  • 40
  • 51