Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove default value of input on focus

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">
like image 863
user342391 Avatar asked Sep 27 '10 17:09

user342391


People also ask

How do you clear the input field on a Ford Focus?

Clear input field on focus This onfocus() event can be used to clear the input field. To do so use onfocus="this. value"=" " within the input field. It will clear the previous value.

How do you clear a text box on focus?

You can use the onfocus attribute in JavaScript to clear a textbox or an input box when somebody sets focus on the field. If you are using jQuery, then use the . focus() method to clear the field.


4 Answers

$(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();
})​
like image 118
RobertPitt Avatar answered Oct 26 '22 22:10

RobertPitt


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 :)

like image 27
clifgriffin Avatar answered Oct 26 '22 22:10

clifgriffin


With HTML5 you could do it without Javascript: just use placeholder instead of value. I think it's a nice addition, but of course you need to check the browser compatibility first.

like image 38
pera Avatar answered Oct 26 '22 22:10

pera


<input type="text" id="anything" placeholder="enter keypress description">

i think this will help

like image 37
kkk Avatar answered Oct 26 '22 23:10

kkk