This almost works. However, when leaving the field \"defaulttext\" appears rather than the original text value. Not sure how to most efficiently echo the variable inside default
var q = $('#q');
q.focus(function() {
if ($(this).attr('data-default') == $(this).val()) {
$(this).val('');
}
}).blur(function() {
if($(this).val() == '') {
$(this).val($(this).attr('data-default'));
}
});
<input type="text" name="q" id="q" data-default="Search..." value="Search..."/>
You need to remove the ' ' marks around the defaultText variable in your set method (val).
Try something along hte lines of
$(function() {
var defaultText = '';
$('input[type=text]').focus(function() {
defaultText = $(this).val();
$(this).val('');
});
$('input[type=text]').blur(function() {
$(this).val(defaultText); // NB removed the ' ' marks
//echo // What are you trying to echo?
});
});
This one will save the default text for you using the .data() function. So no need for extra markup.
$('input').focus(function() {
if (!$(this).data("DefaultText")) $(this).data("DefaultText", $(this).val());
if ($(this).val() != "" && $(this).val() == $(this).data("DefaultText")) $(this).val("");
}).blur(function(){
if ($(this).val() == "") $(this).val($(this).data("DefaultText"));
});
I funetuned this code little bit.
$(document).ready(function () {
var defaultText = '';
$('.input-focus-clear').focus(function () {
defaultText = $(this).val();
$(this).val('');
});
$('.input-focus-clear').blur(function () {
var newText = $(this).val();
if (newText.length < 1) {
$(this).val(defaultText);
}
});
});
Use HTML5 attribute placeholder on each input tag, eg:
<input type="text" value="original text value" placeholder="default value" />
You're not referencing the variable defaultText
. You're passing a string since it's wrapped in quotes.
$(function() {
var defaultText = $('input[type=text]').val();
$('input[type=text]').focus(function() {
$(this).val('');
});
$('input[type=text]').blur(function() {
$(this).val(defaultText); // fixed!
});
});