Default Field Value Text Replace


/ Published in: JavaScript
Save to your folder(s)

A simple plugin to set an "inner" label on text inputs.


Copy this code and paste it in your HTML
  1. /* Usage:
  2.  *
  3.  * HTML: <input class="default-value-replace" data-placeholder="Search" type="text" name="some_name">
  4.  * JS: $('#form').inputLabeler();
  5.  */
  6.  
  7. (function($) {
  8.  
  9. $.inputLabeler = function(element, options) {
  10.  
  11. var defaults = {
  12. inputClass: 'default-value-replace',
  13. dataTag: 'placeholder'
  14. };
  15.  
  16. var plugin = this;
  17.  
  18. plugin.settings = {};
  19.  
  20. var $element = $(element),
  21. element = element;
  22.  
  23. plugin.init = function() {
  24.  
  25. plugin.settings = $.extend({}, defaults, options);
  26.  
  27. var _theInputs = [],
  28. _theSubmitButton = $element.find('input[type="submit"]');
  29.  
  30. (function(){
  31. $element.find('input.' + plugin.settings.inputClass ).each(
  32. function(){
  33.  
  34. var _input = $(this),
  35. defaultValue = _input.data( plugin.settings.dataTag );
  36.  
  37. if ( defaultValue != '') {
  38. _input
  39. .val( defaultValue )
  40. .on( 'focusin focusout', function() {
  41. if ( $.trim( _input.val() ) == '' ) {
  42. _input.val( defaultValue );
  43. } else if ( $.trim( _input.val() ) == defaultValue ) {
  44. _input.val('');
  45. };
  46. });
  47. _theInputs.push( _input );
  48. };
  49. });
  50. })();
  51.  
  52. _theSubmitButton
  53. .click(function(){
  54.  
  55. defaultValueSubmitted = false;
  56.  
  57. $.each( _theInputs, function(){
  58.  
  59. var _input = $(this),
  60. defaultValue = _input.data( plugin.settings.dataTag );
  61.  
  62. if ( $.trim( _input.val() ) == defaultValue ) {
  63. defaultValueSubmitted = true;
  64. }
  65. });
  66.  
  67. if ( ! defaultValueSubmitted ) {
  68. plugin.submit();
  69. } else {
  70. return false;
  71. };
  72.  
  73. });
  74. };
  75.  
  76. plugin.init();
  77.  
  78. };
  79.  
  80. $.fn.inputLabeler = function( options ) {
  81. return this.each(
  82. function() {
  83. var _this = $(this);
  84. if ( undefined == _this.data( 'inputLabeler' )) {
  85. var plugin = new $.inputLabeler( this, options );
  86. _this.data( 'inputLabeler', plugin );
  87. }
  88. });
  89. };
  90.  
  91. })(window.jQuery);

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.