TechRemarker
TechRemarker

Reputation: 2938

Clear input on focus with jQuery and return on blur

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 defaultText.

$(function() {
    var defaultText = $(this).val();
    $('input[type=text]').focus(function() {
      $(this).val('');
      });
     $('input[type=text]').blur(function() {
      $(this).val('defaultText');
      echo 
      });
 });

Upvotes: 6

Views: 35984

Answers (13)

user17502415
user17502415

Reputation: 1

    $("input[type=text]").focus(function () {
        $(this).attr("data-old-input", $(this).val());
        $(this).val("");

    });

    $("input[type=text]").blur(function () {
        $(this).val($(this).attr("data-old-input"));
        $(this).attr("data-old-input", "");
    });

Upvotes: 0

Tarmo
Tarmo

Reputation: 11

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);
        }
    });
});

Upvotes: 1

Andreas
Andreas

Reputation: 73

This is working! I use it myself:

/* Forminputs löschen und wiederherstellen */
jQuery(function() {
    var input = jQuery('#userForm input[type=text], #userForm textarea');

    input.focus(function() {

        jQuery(this).attr('data-default', jQuery(this).val());
        jQuery(this).val('');

    }).blur(function() {
        var el = jQuery(this);

        if (el.val() == '')
            el.val(el.attr('data-default'));
    });
});

Upvotes: 0

Zamir
Zamir

Reputation: 441

   $('.myclass').each(function() {
    var default_value = this.value;
    $(this).css('color', '#666'); // this could be in the style sheet instead
    $(this).focus(function() {
        if(this.value == default_value) {
            this.value = '';
            $(this).css('color', '#333');
        }
    });
    $(this).blur(function() {
        if(this.value == '') {
            $(this).css('color', '#666');
            this.value = default_value;
        }
    });
});
<input type="text" class="myclass" size="30" value="type here" />

Upvotes: 0

Alex
Alex

Reputation: 35409

$(function() {
    var input = $('input[type=text]');

    input.focus(function() {
         $(this).val('');
    }).blur(function() {
         var el = $(this);

         /* use the elements title attribute to store the 
            default text - or the new HTML5 standard of using
            the 'data-' prefix i.e.: data-default="some default" */
         if(el.val() == '')
             el.val(el.attr('title'));
    });
 });

Update

Browsers are progressively implementing the placeholder attribute, which provides the ability to display a "hint" to the user.

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input#attr-placeholder

Upvotes: 13

Djesse
Djesse

Reputation: 21

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"));
});

Upvotes: 2

lokers
lokers

Reputation: 2198

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..."/>

Upvotes: 0

mattdlockyer
mattdlockyer

Reputation: 7314

This solution requires jQuery!

I wrapped this functionality up in a utils module like so:

var utils = (function () {
    var utils = {};
    //some other properties...
    utils.setupAutoclearInputs = function() {
        $('.input-autoclear').each(function() {
            $(this).data('default', $(this).val()).addClass('gray');
        }).focus(function(e) {
            if (!($(this).val() !== $(this).data('default'))) {
                $(this).removeClass('gray').addClass('black').data('modified', true).val('');
            }
        }).blur(function(e) {
            if (!($(this).val() !== $(this).data('default')) || $(this).val() === '') {
                $(this).removeClass('black').addClass('gray').val($(this).data('default'));
            }
        });
    }
    //some other methods...
    return utils;
}());

In the HTML:

Add: class="input-autoclear" to each input you wish to be included.

Set the default value: <input ... value="defaultValue" ... >

Create some css classes for gray and black text or whatever you want.

Personally I'm using .gray { ... } and .black { ... } but you might want better names.

Finally:

Fire the utils modules method using:

$(document).ready(function() {
    ...
    utils.setupAutoclearInputs();
    ...
}

Make sure the code for the module lives outside the document.ready call and you will probably want it in the global scope of your application.

For more on proper javascript module writing, visit this article.

Upvotes: 2

Tici
Tici

Reputation: 116

Use HTML5 attribute placeholder on each input tag, eg:

<input type="text" value="original text value" placeholder="default value" />

Upvotes: 1

shaunsantacruz
shaunsantacruz

Reputation: 8930

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!
      });
 });

Upvotes: 0

clime
clime

Reputation: 8885

Try this in your firebug:

$(function() { console.log($(this)) });

You will find out that

var defaultText = $(this).val();

is probably not what you want.

If initial value for the input is the default text, obtain it like this:

var defaultText = $('input[type=text]').val()

Be aware, that this will work correctly only if there is just one input text on your page.

And also remove quotes in:

$(this).val('defaultText');

Upvotes: 0

Dave Walker
Dave Walker

Reputation: 3523

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? 
     });
 });

Upvotes: 2

Jonas m
Jonas m

Reputation: 2734

Simpl write $(this).val(defaultText): without the ''s else it wont treat it as a variable.

Upvotes: 1

Related Questions