2

I have a textbox that has a piece of text in it already so users know what is supposed to go in it. I've already set it up so clicking on it selects all the text. What I want to know if how I can make it so clicking on the textbox will clear all the text. Likewise, if the user deletes everything they wrote, how can I make the original text appear?

A perfect example of what I want to do is the textbox for the title when asking a question here on Stack Overflow.

3 Answers 3

3

With the code below you can simply add the class "clear" to any input element or textarea and it will clear the initial value!!!

<!DOCTYPE html>    
<html>
    <head>
    <title>Sample</title>
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.min.js" type="text/javascript"></script>
    <script>
    $(function() {
      $('.clear').one('focus', function() {
        this.value = '';
      });
    });
    </script>
    </head>
    <body>
    <input type="text" value="Full Name" class="clear"/> <br />
    <input type="text" value="Email" class="clear"/> <br />
    <textarea value="About you..." class="clear"></textarea>
    </body>
    </html>
Sign up to request clarification or add additional context in comments.

2 Comments

I'm a beginner at this, would you mind explaining? Many thanks!
Sure, are you using a Javascript library like JQuery? This would make tasks like this much more efficient and easier to do. If you like, I will change the answer to accomplish a complete solution using JQuery
2

Fast and dirty, but does the job:

<input type="text" value="init..." onfocus="this.value=''; this.onfocus=null;" />

Update:

Since my answer in 2011 input placeholder became a common thing, so the proper solution is:

<input type="text" placeholder="init..." />

1 Comment

it's perfect! fast and easy!
0

The textarea you created should have an id associated with it in the tag. The text area id would look something like this:

<textarea id="someId"...>

Where "someId" would be whatever name you give to it. Then when you use the following code

document.getElementById('someId').value = '';

it will replace the text in the box with the text specified by the function above. In this case, it will replace it with no text. Just make sure it only does this once, otherwise, when you click outside of the box, and then click inside of it again, the user's input will still be erased as well.

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.