You can use the attribute placeholder
to put the text that will only appear when the field is empty:
<input type="text" placeholder="Pesquisar..." name="q" id="s" onfocus="defaultInput(this)" onblur="clearInput(this)" />
According to the caniuse with. this attribute is supported by every browser in its current version, except Opera Mini (IE9 or earlier does not support).
If you need a solution to work in older browsers, I suggest using the functions themselves onfocus
and onblur
to address this - upon receiving the focus, the placeholder is hidden; upon losing the focus, if the value size is zero the placeholder is reset. (the alternative would be to do this in the onkeyup
, so that only when the user even start typing the placeholder would disappear, but I don’t think it’s a good idea, for several reasons)
You would still have to store somewhere the "input is empty or not?" information to decide whether what is in the input
is a placeholder or just one text that by coincidence is equal to placeholder... In the absence of a better place, I suggest to put as an attribute data-*
. Ex.:
<input type="text" value="Pesquisar..." data-vazio="sim" name="q" id="s" onfocus="defaultInput(this)" onblur="clearInput(this)" />
And of course, keep this attribute updated as the user modifies the input
(this can be done on own onblur
, or maybe in the onchange
).
Updating: or better yet, use a CSS class to monitor this, so beyond the control you need you still get "for free" the opportunity to change the style of the input (for example, making the letter gray if only the placeholder is there).
<input type="text" value="Pesquisar..." class="vazio" name="q" id="s" onfocus="defaultInput(this)" onblur="clearInput(this)" />
CSS:
input.vazio {
color: lightgray;
}
(recalling that an element may have more than one class, if necessary: class="classe1 classe2 classe3"
)
To resolve the lack of IE9 support for the placeholder attribute, just use the jQuery - http://mths.be/placeholderplugin
– user622