Placing text and controls inside text input in Bootstrap 2.3.2

I wanted to place an “x” inside a text input. Bootstrap offers something like this, except in Bootstrap the additional control is attached to the left or right of the input, it is not inside the input.

For example this is what Bootstrap does:

bootstrap-attach-control
What I want is this:

composite-input

The short of it I managed to do it by making changes to Bootstrap. I added the following to bootstrap.less:

.composite-input {
    color: @placeholderText;
    display: inline-block;
    vertical-align: top;
    margin-bottom: 10px;

    &.focus { /* class assigned by jQuery below to create focus effect */
        border-color: rgba(82,168,236,.8);
        outline: 0;
        outline: thin dotted \9; /* IE6-9 */
        .box-shadow(~"inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6)");
    }

    > input {
        margin-bottom: 0;
        margin-top: -3px;
        padding: 0;
        border: none;
        outline: 0;
        -webkit-box-shadow: none;
        -moz-box-shadow: none;
        box-shadow: none;

        &:focus {
            -webkit-box-shadow: none;
            -moz-box-shadow: none;
            box-shadow: none;
        }
    }
}

I also added .composite-input to two lists of input selectors in forms.less. Basically where ever you find a style for input[type="text"].

Finally I added some jquery code to bootstrap.js in order to among other things apply the focus effect:

  $(".composite-input").click(function (event) {
      if(event.target == this) {
        $(this).find("input").focus();
      }
  });
  $(".composite-input .focus-input").click(function () {
      $(this).parent(".composite-input").find("input").focus();
  });
  $(".composite-input > input").focus(function () {
      $(this).parent(".composite-input").addClass("focus");
  });
  $(".composite-input > input").blur(function () {
      $(this).parent(".composite-input").removeClass("focus");
  });

In addition to the focus effect, which in the default Bootstrap settings means a blue outer glow. The jQuery code also add the behavior that if you click in the general textbox the input field will be focused. You can also add the focus-input class to any child element to cause the input to be focused when it’s clicked.
This is the code I used to create the Filter textbox with the x above:

    <div class="composite-input">
        <span class="focus-input">Filter:</span> 
        <input type="text" /> 
        <span>×</span>
    </div>

If you like what you’ve read sign up for my mailing list.

Leave a Reply

Your email address will not be published. Required fields are marked *