views:

27

answers:

2

I have an input box that has default value text assigned to it. How can I remove this text when the user focuses on the field::

CoDE

<input type="text" name="kp1_description" value="Enter Keypress Description">
+2  A: 

Don't do it this way. Use a jQuery watermark script: http://code.google.com/p/jquery-watermark/

$("input[name='kp1_description']").watermark("Enter Keypress Description");

There are a lot of things you have to account for if you do it manually. For instance, what happens when the text box loses focus? If there's no value, you'd want to readd your helper text. If there is, you'd want to honor those changes.

Just easier to let other people do the heavy lifting :)

clifgriffin
but using a whole library for a simple task is not the best idea.
RobertPitt
True, I'm just of the opinion that this wheel doesn't need to be reinvented. There are lots of scenarios you have to consider and using the library can simplify that a lot. He tagged his question with jQuery so using a jQuery plugin is probably the most pragmatic way to accomplish this task.
clifgriffin
+1 for code reuse. Some problems are hard and should be solved by a library and not reimplemented badly by every code monkey on the planet. People are especially bad about this when it comes to javascript.
Sorpigal
+1  A: 
$(document).ready(function(){
    var Input = $('input[name=kp1_description]');
    var default_value = Input.val();

    Input.focus(function() {
        if(Input.val() == default_value) Input.val("");
    }).blur(function(){
        if(Input.val().length == 0) Input.val(default_value);
    });
})​

That should do it.

Updated, Forgot that focus does not have a 2nd parameter for the focus-out event because there is none, it has to be chained with blur:

http://jsfiddle.net/hDCsZ/

you should also think about creating your own function for this such as:

$.fn.ToggleInputValue = function(){
    return $(this).each(function(){
        var Input = $(this);
        var default_value = Input.val();

        Input.focus(function() {
           if(Input.val() == default_value) Input.val("");
        }).blur(function(){
            if(Input.val().length == 0) Input.val(default_value);
        });
    });
}

Then use like so

$(document).ready(function(){
    $('input').ToggleInputValue();
})​
RobertPitt
The value doesn't reappaear if nothing has been entered.hmm..
Updated, Let me know if that works.
RobertPitt
weird still nothing
Updated again, sorry im half asleep :)
RobertPitt