Clear input on focus with jQuery and return on blur

后端 未结 12 2560
耶瑟儿~
耶瑟儿~ 2021-02-09 17:50

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

12条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-09 18:22

    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:

    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.

提交回复
热议问题