Automatically replacing text in HTML textbox
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 te开发者_JAVA技巧xt. 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.
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>
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..." />
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.
精彩评论