/ Published in: JavaScript
A simple plugin to set an "inner" label on text inputs.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/* Usage: * * HTML: <input class="default-value-replace" data-placeholder="Search" type="text" name="some_name"> * JS: $('#form').inputLabeler(); */ (function($) { $.inputLabeler = function(element, options) { var defaults = { inputClass: 'default-value-replace', dataTag: 'placeholder' }; var plugin = this; plugin.settings = {}; var $element = $(element), element = element; plugin.init = function() { plugin.settings = $.extend({}, defaults, options); var _theInputs = [], _theSubmitButton = $element.find('input[type="submit"]'); (function(){ $element.find('input.' + plugin.settings.inputClass ).each( function(){ var _input = $(this), defaultValue = _input.data( plugin.settings.dataTag ); if ( defaultValue != '') { _input .val( defaultValue ) .on( 'focusin focusout', function() { if ( $.trim( _input.val() ) == '' ) { _input.val( defaultValue ); } else if ( $.trim( _input.val() ) == defaultValue ) { _input.val(''); }; }); _theInputs.push( _input ); }; }); })(); _theSubmitButton .click(function(){ defaultValueSubmitted = false; $.each( _theInputs, function(){ var _input = $(this), defaultValue = _input.data( plugin.settings.dataTag ); if ( $.trim( _input.val() ) == defaultValue ) { defaultValueSubmitted = true; } }); if ( ! defaultValueSubmitted ) { plugin.submit(); } else { return false; }; }); }; plugin.init(); }; $.fn.inputLabeler = function( options ) { return this.each( function() { var _this = $(this); if ( undefined == _this.data( 'inputLabeler' )) { var plugin = new $.inputLabeler( this, options ); _this.data( 'inputLabeler', plugin ); } }); }; })(window.jQuery);