This solution requires jQuery!
I wrapped this function in the utils module as follows:
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 HTML:
Add: class="input-autoclear" to each input you want to include.
Set the default value: <input ... value="defaultValue" ... >
Create some CSS classes for gray and black text or whatever.
Personally, I use .gray { ... } and .black { ... } , but you may need better names.
Finally:
Run the utils modules method using:
$(document).ready(function() { ... utils.setupAutoclearInputs(); ... }
Make sure that the code for the module lives outside the document.ready document, and you probably want it in the global area of your application.
Read more about how to write javascript modules correctly in the article.
source share