Reputation: 494
I create a field with this code
<tr><td> <input type="text" value="good" onfocus="if (this.value == 'good') {this.value=''}" onblur="if(this.value == '') { this.value='good'}" name="name" maxlength="254" class="required" /></td></tr>
when user click on field then we have clear and empty field.and if user put field empty we write back this good
value.but that's not what I want, I am looking for some way like user registration form in facebook then if user type a character we clear value and if user keep field empty we will fill in this field with default value..can someone help me with this javascript or jquery?
Upvotes: 0
Views: 84
Reputation: 4094
Try changing your input to:
<tr>
<td>
<input type="text" value="good" placeholder="good" name="name" maxlength="254" class="required defaultText" />
</td>
</tr>
And add some jQuery code:
$(document).ready(function() {
$(".defaultText").focus(function(srcc) {
if ($(this).val() == $(this)[0].placeholder) {
$(this).val("");
}
});
$(".defaultText").blur(function() {
if ($(this).val() == "") {
$(this).val($(this)[0].placeholder);
}
});
$(".defaultText").blur();
});
The defaultText
style class, is used to select the html elements, and the placeholder
in the element is defining the default value for it.
Edit: Changed title
for placeholder
, this way it will be compatible with html5 or previous
Upvotes: 1
Reputation: 1427
If placeholder attributes aren't viable you could use the onkeydown event instead of onfocus.
Upvotes: 1
Reputation: 74058
You could just use the placeholder
attribute for that
<tr>
<td>
<input type="text" placeholder="good" name="name" maxlength="254" class="required" />
</td>
</tr>
This shows as long as the user hasn't input text, but it doesn't change the value
attribute.
JSFiddle for testing.
Upvotes: 1