Thursday, February 27, 2014

A Clear Text Input Widget

A standard requirement of most user interfaces is that the input elements have a clear text button. This is generally rendered as a small "x" on the right side of the input. When the user clicks this "x" icon, any text entered in the input is removed. It makes sense to add such a capability into a widget since you'll be applying it to input elements throughout the application. Let's see how this is done using jQuery UI.

As you can see, this input looks like your typical element found in any web application. The benefit of the jQuery UI approach is that there's a theme framework — I can easily make the input styles match the icon style. That's mostly just the color, but it's still one less step. The tricky part is positioning the icon. And for that, we have the position utility. Here's what the widget declaration looks like.

var widgetClasses = [
].join( " " ),
iconClasses = [
].join( " " );
$.widget( "app.cleartext", {
    _create: function() {
        this.element.addClass( widgetClasses );
        this.$icon = $( "<span/>" )
            .addClass( iconClasses )
            .appendTo( "body" )
                at: "right-12",
                of: this.element
        this._on( this.$icon, {
            click: "_clear"    
    _destroy: function() {
        this.element.removeClass( widgetClasses );
    _clear: function( e ) {
        this.element.val( "" ).focus();

We start by defining variables to hold class names. This a simple code readability tactic — we could just as easily have a string literal where we're using the classes. The widgetClasses variable holds the class names applied to the input element itself. The iconClasses variable has the classes applied to the icon span element.

Moving on to the widget declaration itself, we have to implement a _create() method — the widget constructor. We want to use _super() here to perform the routine widget setup tasks. Next, we add the widgetClasses to the input element, then the iconClasses to the span element. The span element gets added the body and positioned relative to this.element using the position utility. The last job of the constructor is to setup the click event on the icon. This event is handled by the _clear() method, which simply empties the text input value, and re-focuses it.

Last but not least, the _destroy() method, called when the widget is destroyed, will remove the icon span from the DOM, and remove the widgetClasses from the input element.