Is there a quick way to create an input text element with an icon on the right to clear the input element itself (like the google search box)?
I looked around but I only found how to put an icon as background of the input element. Is there a jQuery plugin or something else?
I want the icon inside the input text element, something like:
--------------------------------------------------
| X|
--------------------------------------------------
Best Answer
Add a
type="search"
to your inputThe support is pretty decent but will not work in IE<10
Older browsers
If you need IE9 support here are some workarounds
Using a standard
<input type="text">
and some HTML elements:Using only a
<input class="clearable" type="text">
(No additional elements)set a
class="clearable"
and play with it's background image:The trick is to set some right padding (I used 18px) to the
input
and push the background-image right, out of sight (I usedright -10px center
).That 18px padding will prevent the text hide underneath the icon (while visible).
jQuery will add the class
"x"
(ifinput
has value) showing the clear icon.Now all we need is to target with jQ the inputs with class
x
and detect onmousemove
if the mouse is inside that 18px "x" area; if inside, add the classonX
.Clicking the
onX
class removes all classes, resets the input value and hides the icon.7x7px gif:
Base64 string: