I found a lot of examples but I'm trying to figure out the simplest way to clear an input's default value when clicking it.
This is for a search box. I have "Search for post" and I want to clear that when clicking on it.
I tried using jquery but for some reason it doesn't work.
$('#search').click(function() {
if($(this).val() == 'Search for post')
$(this).val('');
});
<input type="text" name="s" id="search" value="Search for post">
Can anyone think of a simpler code?
For an input, you want to use
.focus()
Live demo: http://jsfiddle.net/rchern/aWdgZ/
It would be interesting to try this with the html5
placeholder
attribute. This would work on all current versions of Safari, Chrome, and Firefox.You then need to add some fallback code for browsers that don't support this feature.
I threw together a jsfiddle to test this out. It seems to work great for those that support it, and other as good as it can be for browsers like IE 6.
http://jsfiddle.net/V2R9J/ (Note: I changed the
trim
to a empty string comparison just to get it to work. You could/should use your own trim function here instead.)Disclaimer : This won't work for fields that are inserted via ajax. You could attempt something with live, or you could manually invoke a method. Also - it work work with
password
fields, since it will just make them show the*
or some other bulleted field, but that was already a problem.This is pretty experimental, but it seems like a really cool solution that allows people who use the newer browsers to get some of the awesome functionality in html5, albeit as simple as it is.