I have an input text :
I want to put a default value like
This is somewhat cleaner, i think. Note the usage of the "defaultValue" property of the input:
<script>
function onBlur(el) {
if (el.value == '') {
el.value = el.defaultValue;
}
}
function onFocus(el) {
if (el.value == el.defaultValue) {
el.value = '';
}
}
</script>
<form>
<input type="text" value="[some default value]" onblur="onBlur(this)" onfocus="onFocus(this)" />
</form>
EDIT: Although, this solution works, I would recommend you try MvanGeest's solution below which uses the placeholder
-attribute and a javascript fallback for browsers which don't support it yet.
If you are looking for a Mootools equivalent to the JQuery fallback in MvanGeest's reply, here is one.
--
You should probably use onfocus
and onblur
events in order to support keyboard users who tab through forms.
Here's an example:
<input type="text" value="email@abc.com" name="Email" id="Email"
onblur="if (this.value == '') {this.value = 'email@abc.com';}"
onfocus="if (this.value == 'email@abc.com') {this.value = '';}" />
Here is a jQuery solution. I always let the default value reappear when a user clears the input field.
<input name="Email" value="What's your programming question ? be specific." type="text" id="Email" value="email@abc.com" />
<script>
$("#Email").blur(
function (){
if ($(this).val() == "")
$(this).val($(this).prop("defaultValue"));
}
).focus(
function (){
if ($(this).val() == $(this).prop("defaultValue"))
$(this).val("");
}
);
</script>
For future reference, I have to include the HTML5 way to do this.
<input name="Email" type="text" id="Email" value="email@abc.com" placeholder="What's your programming question ? be specific." />
If you have a HTML5 doctype and a HTML5-compliant browser, this will work. However, many browsers do not currently support this, so at least Internet Explorer users will not be able to see your placeholder. However, see http://www.kamikazemusic.com/quick-tips/jquery-html5-placeholder-fix/ (archive.org version) for a solution. Using that, you'll be very modern and standards-compliant, while also providing the functionality to most users.
Also, the provided link is a well-tested and well-developed solution, which should work out of the box.
Just use a placeholder
tag in your input instead of value
Here is an easy way.
#animal
represents any buttons from the DOM.
#animal-value
is the input id that being targeted.
$("#animal").on('click', function(){
var userVal = $("#animal-value").val(); // storing that value
console.log(userVal); // logging the stored value to the console
$("#animal-value").val('') // reseting it to empty
});