Last active
August 29, 2015 14:02
-
-
Save sukima/998885b6d8142873e88f to your computer and use it in GitHub Desktop.
Add clear button to text inputs jQuery plugin for Bootstrap
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
# A jQuery plugin to add an X to the text input to clear it's content. | |
# Uses bootstrap for styling and glyphicons. | |
# | |
# ## Options | |
# | |
# icon - The glyphicon name (including the `glyphicon-` prefix. See examples. | |
# Use `false` to disable icon. Default `glyphicon-remove`. | |
# html - Any custom HTML you wish to have in the button. Default none. | |
# | |
# ## Examples | |
# | |
# $("input[type=text]").inputClear(); | |
# | |
# $(".clearable-inputs").inputClear({ | |
# icon: "glyphicon-ban-circle" | |
# }); | |
# | |
# $("#search").inputClear({ | |
# icon: false, | |
# html: "<b>X</b>" | |
# }); | |
# | |
$ = jQuery | |
$.fn.inputClear = (options={}) -> | |
@each (i, input) -> | |
input = $(input) | |
clearButton = input.data("clear-button") | |
init = -> | |
icon = options.icon ? "glyphicon-remove" | |
iconHtml = if icon | |
"""<span class="glyphicon #{icon}"></span>""" | |
else | |
"" | |
html = options.html || "" | |
html = " #{html}" if icon && options.html | |
clearButton = $("""<a href="#">#{iconHtml}#{html}</a>""") | |
.css | |
display: "inline" | |
cursor: "pointer" | |
color: "#888" | |
position: "absolute" | |
top: input.position().top | |
left: input.position().left + input.outerWidth() | |
margin: "8px 0px 0px -20px" | |
.on "click", (e) -> | |
e.preventDefault() | |
input | |
.val("") | |
.trigger "change" | |
.focus() | |
showHideButton() | |
input.data("clear-button", clearButton) | |
.on("keyup", showHideButton) | |
.after(clearButton) | |
showHideButton() | |
showHideButton = -> | |
clearButton.toggle(input.val() != "") | |
init() unless clearButton? | |
this |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment