jQuery Swaptextbox Script

Nov 18, 2011 2:24 pm

Have an input box, like a search box, that you want to swap the contents of, but don't have a script to do it? Just assign it the class "swaptextbox" use this little snippet (and jQuery):

jQuery('.swaptextbox').each(function() {
    var that = jq(this);
    that.click(function () {
        if (that.data('clickedBefore') !== true) {
            that.data('clickedBefore', true);
            that.data('shouldReturn', true);
            if (!that.data('originalText')) {
                that.data('originalText', that.val());
            }
            that.val('');
        }
    }).keyup(function() {
        if (that.val() !== '') {
            that.data('shouldReturn', false);
        } else {
            that.data('shouldReturn', true);
        }
    }).focusout(function () {
        if (that.data('shouldReturn') === true || that.val() === '') {
            that.val(that.data('originalText'));
            that.data('clickedBefore', false);
        }
    });
});

Thanks to the magic of jQuery.data, text in an input box with a class of swaptextbox will disappear when an input box receives focus and reappear when the box loses focus if there's nothing in it. You can try it out on this site, but beware! It's still in the works. Click in the 'enter search terms' input box for a sample.

And, yes, this is a really simple thing, but sometimes it's nice to have a ready-made snippet you can use.

Dec 1, 2011 11:51 am

I noticed a tiny issue with this, so here's a changed version:

jQuery('.swaptextbox').each(function() {
    var that = jQuery(this);
    that.click(function () {
        if (that.data('clickedBefore') !== true) {
            that.data('clickedBefore', true);
            that.data('shouldReturn', true);
            if (!that.data('originalText')) {
                that.data('originalText', that.val());
            }
            that.val('');
        }
    }).keyup(function() {
        if (that.val() !== '') {
            that.data('shouldReturn', false);
        } else {
            that.data('shouldReturn', true);
        }
    }).focusout(function () {
        if (that.data('shouldReturn') === true || that.val() === '') {
            that.val(that.data('originalText'));
            that.data('clickedBefore', false);
        }
    });
});

I use 'jq' as an alias for jQuery in self-invoking functions (or closures or whatever you want to call them)--sorry I missed that one!

Mar 22, 2015 11:29 pm

Thanks for this :)