Reputation: 1291
I have a text box which have initial value written in, i wanna that box to be clear when it is clicked(active).
Ex: //wanna it to be clear when clicked to enter a value from user
Upvotes: 1
Views: 7792
Reputation: 50095
Neither of the above solutions are very good - inline events is not a good solution in this case. What you'll want is to use the HTML5 placeholder
attribute, and with a bit of Javascript, add support for it for browsers that do not support it. Your HTML will look something like this:
<input type="text" placeholder="Search" id="search" />
This will work with the current versions of Safari and Chrome. For the other browsers, you can use this Javascript:
// Creates a new element and check if it has the 'placeholder' property
// If it does not, then we know that the browser does not support HTML5 placeholder
if(typeof document.createElement('input').placeholder === 'undefined'){
// Find the input element with the id "search" and get the 'placeholder' attribute
var input = document.getElementById('search'),
p = input.getAttribute('placeholder');
// Give it the placeholder value
input.value = p;
// Clear input on focus, then add the placeholder text
// back in if there's nothing there after the user changes edits the box
input.onfocus = function(){
if(this.value === p) this.value = '';
}
input.onblur = function(){
if(!this.value) this.value = p;
}
}
You can see a simple demo of this here: http://jsfiddle.net/RT8Bf/
Upvotes: 4
Reputation: 15344
just write
<input type='text' name='myText' onFocus='this.value="";'/>
UPDATED:
if you want value back if nothing is entered
<input type="text" onfocus="if(this.value=='Search') this.value='';" onblur="if(this.value=='') this.value='Search';" value="Search" />
Upvotes: 3
Reputation: 4934
You can do this with javascript look at the onclick event. Here a small example:
<input type="text" onclick="this.value='';" />
Upvotes: 1