Create a Clearable TextBox with jQuery

Recently I came across a wonderful article by David Walsh on Clearable Textboxes with Dojo Toolkit [link]. This is a simple implementation where a clear button (x) added in a textbox which lets user to clear the content of the textbox. I have seen this simple feature in many websites and feel its very useful to have. It increase the usability of form.

I thought to implement the same feature using jQuery. Here is a simple plugin that I wrote to add clearable feature to any textbox in your HTML form. All you need is to call clearable() method on the textbox. For example.

<script type="text/javascript" src="jquery.clearable.js"></script>
<link rel="stylesheet" href="jquery.clearable.css"
       type="text/css" media="screen" />
<input type="text"  class="foo"></input>
$(document).ready(function() {

In above example we included jquery.clearable plugin javascript and stylesheet files. Then called .clearable() method on the textboxes we want to add clearable feature. That’s it

Let us go through the code and see what exactly goes behind the scene in jquery clearable plugin.


We use following stylesheet classes internally to display the

.divclearable {
    border: 1px solid #888;
    display: -moz-inline-stack;
    display: inline-block;
a.clearlink {
    background: url("close-button.png") no-repeat scroll 0 0 transparent;
    background-position: center center;
    cursor: pointer;
    display: -moz-inline-stack;
    display: inline-block;
    height: 12px;
    width: 12px;
    z-index: 2000;
    border: 0px solid;

There are two css classes we uses in clearable plugin. First one is for a wrapper DIV which wraps around the textbox and clear button (x). And the style class is for clear button (x).

The JavaScript

The important bit of the plugin is javascript code that creates clearable effect. For everytextbox, we wrap it around a DIV container and also add one clear button (x) in this container DIV.

Here is the jQuery code:

$(this).css({'border-width': '0px', 'outline': 'none'})
    .wrap('<div id="sq"></div>')
    .attr('class', $(this).attr('class') + ' divclearable')
    .append('<a href="javascript:"></a>');
    .attr('title', 'Click to clear this textbox')
    .click(function() {

In above javascript code, we do:

  1. Remove border and outline of the textbox where we want to add clearable feature
  2. Create a DIV wrapper and wrap the textbox with that DIV
  3. Add the textbox style class to DIV, so the border / background etc that are specified on textbox are added to DIV
  4. Create a link for clear text(x) and append in the DIV

Also for each clear text link (x) we add an onclick handler where we clear the corresponding textbox and set focus in it.

Download jQuery Clearable Plugin

  • 3158 View
  • Pin It