Created
July 26, 2012 23:56
-
-
Save tirams/3185303 to your computer and use it in GitHub Desktop.
jQuery plugin to auto show button to clear input field
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
jQuery plugin that sets up input fields with styling and a 'dismiss' icon. | |
any input elements with clearable class get an icon that shows when there is data in the input | |
clicking the icon clears the input and triggers a 'cleared' event and sets focus to input | |
*/ | |
;(function ($, window, document, undefined) { | |
var pluginName = 'setupClearables', defaults = {}; | |
function updateClearButton(x) | |
{ | |
if (x.value == "" || x.value == $(x).attr('placeholder')) | |
{ | |
$(x).siblings('img').addClass('hide'); | |
} | |
else | |
{ | |
$(x).siblings('img').removeClass('hide'); | |
} | |
} | |
function Plugin( element, options ) { | |
this.element = element; | |
this.options = $.extend( {}, defaults, options ); | |
this._defaults = defaults; | |
this._name = pluginName; | |
this.init(element); | |
} | |
Plugin.prototype.init = function(){ | |
var funcElem = $(this.element); | |
funcElem.find('.clearableInput').wrap('<span class="clearwrapper UserInput"></span>') | |
.after('<img class="clearsearch hide" title="Clear input" ' + | |
' src="/css/themes/classic/images/icons/clearsearch.png" ' + | |
' alt="clear the input" />'); | |
$(function () | |
{ | |
// after doc ready allow more time for any programmatic input value setting | |
// then update the clearable items to show the image or not | |
setTimeout(function () | |
{ | |
funcElem.find('.clearableInput').each(function (x, e) | |
{ | |
updateClearButton(e); | |
}); | |
}, 10); | |
}); | |
//when the clear box is clicked clear the input field, the button and set focus and trigger an event | |
funcElem.find('img.clearsearch').click(function () | |
{ | |
var inp = $(this).siblings('.clearableInput') | |
inp.val(''); | |
updateClearButton(inp[0]); | |
inp.focus(); | |
inp.trigger("cleared"); | |
}); | |
// listen for any input changes to update the icon | |
funcElem.find('.clearableInput').bind('propertychange keyup input paste', function (x) | |
{ | |
setTimeout(function () | |
{ //allow for input to change from action | |
updateClearButton(x.target); | |
}, 10); | |
}) | |
} | |
$.fn[pluginName] = function ( options ) { | |
return this.each(function () { | |
if (!$.data(this, 'plugin_' + pluginName)) { | |
$.data(this, 'plugin_' + pluginName, | |
new Plugin( this, options )); | |
} | |
}); | |
} | |
})(jQuery, window, document); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment