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?

3

3 Answers 3

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

});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but doesnt that just mean the focusout function would just get a blank valvalue (ie not the value obtained in the first, focus function)?
No "focus out" without "focus" :)
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); 
            }
        });

    });

Comments

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">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.