Michaël Perrin

Sustainable web development.

Clear input control with Bootstrap 3

Input clear controls are common to mobile app interfaces where they are native but not so common on the web. Which is too bad as most users click on the field, and type the return key until the field gets cleared. This post explains how to implement a simple clear input control using Bootstrap 3.

The following rules are implemented:

  • Only show the the clear button if the field is not empty
  • Hide Microsoft Internet Explorer default clear button (that doesn't always work the way you would expect by the way)
  • Trigger a cleared event on the input when the clear button has been

The clear control is rendered as a form input feedback icon (as described on the Bootstrap documentation)

SASS / LessCSS:

.has-feedback.has-clear {
    /* Remove Internet Explorer native clear button */
    input::-ms-clear {
        display: none;
    }

    .form-control-clear {
        color: #bbb;
        color: rgba(0, 0, 0, 0.4);

        /*
         * Enable pointer events as they have been disabled since Bootstrap 3.3
         * See https://github.com/twbs/bootstrap/pull/14104
         */
        pointer-events: auto;

        &:hover {
            color: #777;
            color: rgba(0, 0, 0, 0.7);
            cursor: pointer;
        }
    }

    &.has-empty-value {
        /* Do not display clear button if field has empty value */
        .form-control-clear {
            display: none;
        }
    }
}

Javascript:

$(document).ready(function() {
    $('.has-clear input').on('change', function() {
        if ($(this).val() == '') {
            $(this).parents('.form-group').addClass('has-empty-value');
        } else {
            $(this).parents('.form-group').removeClass('has-empty-value');
        }
    }).trigger('change');

    $('.has-clear .form-control-clear').on('click', function() {
        var $input = $(this).parents('.form-group').find('input');

        $input.val('').trigger('change');

        // Trigger a "cleared" event on the input for extensibility purpose
        $input.trigger('cleared');
    });
});

HTML :

<div class="form-group has-feedback has-clear">  
    <label class="control-label" for="inputClear">Input with clear</label>
    <input type="text" class="form-control" id="inputClear">
    <span class="glyphicon glyphicon-remove-sign form-control-feedback form-control-clear" aria-hidden="true"></span>
    <span class="sr-only">Clear input content</span>
</div>  

Demo

Michaël Perrin

Read more posts by this author.

comments powered by Disqus