left-icon

Twitter Bootstrap Succinctly®
by Peter Shaw

Previous
Chapter

of
A
A
A

CHAPTER 5

Forms

Forms


The features added for forms and webpage interaction in TWB are, put simply, nothing short of stunning. There is just so much stuff to cover that it really does deserve an entire chapter unto itself.

Before Twitter Bootstrap came along, I could easily spend a large chunk of my time on the UI of an application, doing nothing more than trying to lay out forms and make everything look nice and lined up.

Any web developer who's ever had to do a form on a webpage will know exactly what I mean, and they’ll know just how painful an experience it can be to get it right.

Best of all, forms marked up under TWB don't need any master class added to the form as you did with tables. All you simply have to do is mark your forms up using recommended semantic HTML 5 layout techniques. TWB will simply just do what it needs to and give you a default, left-aligned, vertically-stacked responsive form.

Start a new template HTML file just as we have done all the way throughout this book, and add the following body content to it:

<div class="container-fluid">

  <div class="row-fluid">

    <h1>Twitter Bootstrap</h1>

    <h3>Forms Example</h3>

    <form>

      <fieldset>

        <legend>My Twitter Bootstrap Form</legend>

        <label>This is a label for the textbox below</label>

        <input type="text" placeholder="Please type something in here">

        <span class="help-block">This is some help text for the control above.</span>

        <label class="checkbox">

          <input type="checkbox"> and here is a nicely lined up check box

        </label>

        <button type="submit" class="btn">Submit</button>

      </fieldset>

    </form>

  </div>

</div>

Code Sample 13: Basic form code

You should have a form in your webpage that looks something like the following once you save and load your document:

Basic Twitter Bootstrap form

As you can see, it takes very little to get something that's visually pleasing to the eye, and as with everything else, you can easily override and customize any individual bits you wish to.

Like the table classes, however, there are a whole load of optional classes you can add to your forms.

Some are designed for special cases such as the search classes, which are designed to make a very modern-looking, rounded search box, right through to the more generic classes for the individual input types.

Search Forms

We've all seen them, and the visually pleased crowd loves them. That’s right, those nice-looking search boxes with the sharply rounded corners and nicely lined up controls that we see on the menu bar of most websites.

Well, using Twitter Bootstrap you can create one of these things in just four lines of HTML 5 markup. Don’t believe me? Try changing the forms example you created just a moment ago to the following:

<div class="container-fluid">

  <div class="row-fluid">

    <h1>Twitter Bootstrap</h1>

    <h3>Forms Example</h3>

    <form class="form-search">

      <input type="text" class="input-medium search-query">

      <button type="submit" class="btn">Search</button>

    </form>

  </div>

</div>

Code Sample 14: Basic form code

If all goes well, you should see the following when you refresh your page:

Search form example

Something else you get for free when you start using the form classes in Twitter Bootstrap is highlighting on the fields themselves. I'll show you more on this soon but, for now, if you click in the search box, you should see it highlight with a blue aura as the following image shows:

Search form example with highlighted field

Search forms are only one specialized example of how TWB can help you; another is the inline forms.

Inline Forms

Inline forms are typically used in places like navigation bars and page headers for elements such as miniature login forms. To make an inline form in Twitter Bootstrap, it should come as no surprise that all you need to do is add yet another class name (I did mention that this was all about CSS and JavaScript).

Change the code sample you made in Code Sample 13 earlier so that it looks like the following code:

<div class="container-fluid">

  <div class="row-fluid">

    <h1>Twitter Bootstrap</h1>

    <h3>Forms Example</h3>

    <form class="form-inline">

      <input type="text" class="input-small" placeholder="Email">

      <input type="password" class="input-small" placeholder="Password">

      <label class="checkbox">

        <input type="checkbox"> Remember me

      </label>

      <button type="submit" class="btn">Sign in</button>

    </form>

  </div>

</div>

Code Sample 13: Inline form code

Save and refresh, and your search form should now have changed to look like this:

Inline form example

As you'll see later when we get to the subject of things like navigation bars, it would be really easy to take this form and add it into your site-wide navigation.

Before we move on to what's available for the individual form controls, let's look at one more type of form: the horizontal form.

Horizontal Forms

To use the horizontal form feature, you add the form-horizontal class to your form. But, unlike the other forms you've seen so far, you have to do a little more work. Different collections of controls need to be wrapped in control groups and your form layout has to be structured in a specific way.

As you dig deeper into TWB, you'll find that there are a few cases where it's about more than just adding the correct classes to your elements. In some cases (particularly when we get to the section on components), it's about the order in which you create your HTML elements and the actual tags you use.

We won't worry about this too much at the moment but it is something that you need to keep at the back of your mind, as you will need to remember it later on.

Before I present you with the next code sample, I'm going to take a moment to introduce you to control groups.

Control Groups

When you create a form normally, you often don't really give it much thought. You just add labels and input fields, and then you add the various buttons and fix up the form handlers to accept your data inputs.

If you look logically at your form from a high level however, through a user’s eyes, you will soon start to see patterns.

The labels above or next to the input fields, the collections of radio buttons, and the rows of buttons all have a separate reason for existing on the page.

If you were to draw boxes around each of these lines, you'd see that you in most cases have a one-column table.

Now, add into the mix things such as validation messages, help text, and other artifacts designed to help the end user navigate the form. Then, consider things such as ARIA compatibility hints for things like screen readers and navigation aids to help those who have impairments. All of a sudden you have a whole jumble of things that require some structure to make related things look related.

The creators of Twitter Bootstrap solved this problem with something called a control group.

A control group is nothing more than a standard <div> tag that surrounds a given row of elements in your form (similar to how a row class works in the base scaffolding). But the other classes in TWB understand and respect the meaning that this parent element has on the controls it contains. We’ll see this in better detail very soon when I cover validation states.

Continuing on with the Horizontal Form

So, getting back to our form examples, change the body code in your form so that it looks like the following:

<div class="container-fluid">

  <div class="row-fluid">

    <h1>Twitter Bootstrap</h1>

    <h3>Form Example</h3>

    <form class="form-horizontal">

      <div class="control-group">

        <label class="control-label" for="inputEmail">Email</label>

        <div class="controls">

          <input type="text" id="inputEmail" placeholder="Email">

        </div>

      </div>

      <div class="control-group">

        <label class="control-label" for="inputPassword">Password</label>

        <div class="controls">

          <input type="password" id="inputPassword" placeholder="Password">

        </div>

      </div>

      <div class="control-group">

        <div class="controls">

          <label class="checkbox">

            <input type="checkbox"> Remember me

          </label>

          <button type="submit" class="btn">Sign in</button>

        </div>

      </div>

    </form>

  </div>

</div>

Code Sample 15: Horizontal form

As with previous examples, if you save and refresh your page, you should see something that looks like this image:

Twitter Bootstrap horizontal form example

As you can see, the use of structure and control groups has made sure that the text label for the check box is neatly lined up, the labels for the input fields are nicely lined up, and the buttons and other furniture all share a common left margin.

With just a few extra lines of code and a sprinkling of classes, your form has a balanced look to it that is pleasing to the eye.

Validation States

If you recall just a moment ago when I was discussing control groups, I mentioned something called validation states.

Validation states are optional classes that you can add to your control groups that then affect every element contained in that group in some visual way, allowing you to convey extra information to the end user about the state of the inputs in the form.

Just like the optional classes you’ve seen previously to style table rows and text items, the validation state classes follow a similar naming convention and default color set that is easily customizable by using the custom download and/or “Less” version of the main TWB style sheet in your project.

The names used by the different validation styles are as follows:

  • warning: Shows the validation state in a yellow warning color.
  • error: Shows the validation state in a red color to indicate an error state.
  • info: Shows the form state in a powder blue color to indicate an informational state.
  • success: Shows the form in a green color to indicate all is okay.

Let's try these states and see what they look like.

In Code Sample 14, change the first control group in your form to include the warning validation state on the first control group in the form. The code should look something like:

<div class="control-group warning">

  <label class="control-label" for="inputEmail">Email</label>

  <div class="controls">

    <input type="text" id="inputEmail" placeholder="Email">

  </div>

</div>

If you then save and refresh your form, you should be greeted with the following:

Horizontal form showing warning state applied to first control

Try changing the warning class to one of the other three and you should see the different colors affecting the entire group. I've added three new controls to my form just to show them all alongside each other.

I've also added the following span:

<span class="help-inline">Example help text</span>

It’s marked up with a help-inline class to each of the <div> tags containing the actual input controls so you can see that the validation state also affects them, too.

Validation states example

Individual Controls Support

Most of the standard input types in the HTML standard are supported, styled, and handled automatically by Twitter Bootstrap. If you use the specific input types added by the HTML 5 specification where browser support permits and styles can be changed, TWB will also attempt to handle the rendered controls appropriately.

Unfortunately, browser support for the new HTML 5 control types is still a little patchy at present. Chrome is considered to be the browser with the best support for the different types at present; however, even that is still a little short of its target.

Don't be put off from using them, though. One of the good things about HTML 5 is that, if the browser does not support the control type you’re trying to render, then it will (or it should) render as a plain old text box instead.

The following code example, while not a Twitter Bootstrap-specific bit of code, shows all the new input types, marked up in appropriate control groups:

  <div class="container-fluid">

    <div class="row-fluid">

      <h1>Twitter Bootstrap</h1>

      <h3>Form Inputs Example</h3>

      <form>

      <div class="control-group">

        <label class="control-label">Text Input</label>

        <div class="controls">

          <input type="text" />

        </div>

      </div>

      <div class="control-group">

        <label class="control-label">Search Input</label>

        <div class="controls">

          <input type="search" />

        </div>

      </div>

      <div class="control-group">

        <label class="control-label">Email Input</label>

        <div class="controls">

          <input type="email" />

        </div>

      </div>

      <div class="control-group">

        <label class="control-label">Url Input</label>

        <div class="controls">

          <input type="url" />

        </div>

      </div>

      <div class="control-group">

        <label class="control-label">Telephone Input</label>

        <div class="controls">

          <input type="tel" />

        </div>

      </div>

      <div class="control-group">

        <label class="control-label">Number Input</label>

        <div class="controls">

          <input type="number" />

        </div>

      </div>

      <div class="control-group">

        <label class="control-label">Range Input</label>

        <div class="controls">

          <input type="range" />

        </div>

      </div>

      <div class="control-group">

        <label class="control-label">Date Input</label>

        <div class="controls">

          <input type="date" />

        </div>

      </div>

      <div class="control-group">

        <label class="control-label">Month Input</label>

        <div class="controls">

          <input type="month" />

        </div>

      </div>

      <div class="control-group">

        <label class="control-label">Week Input</label>

        <div class="controls">

          <input type="week" />

        </div>

      </div>

      <div class="control-group">

        <label class="control-label">Time Input</label>

        <div class="controls">

          <input type="time" />

        </div>

      </div>

      <div class="control-group">

        <label class="control-label">Datetime Input</label>

        <div class="controls">

          <input type="datetime" />

        </div>

      </div>

      <div class="control-group">

        <label class="control-label">Datetime local Input</label>

        <div class="controls">

          <input type="datetime-local" />

        </div>

      </div>

      <div class="control-group">

        <label class="control-label">Color Input</label>

        <div class="controls">

          <input type="color" />

        </div>

      </div>

      </form>

    </div>

  </div>

Code Sample 16: HTML 5 input control types

If I render this in my default copy of Chrome (Version 28.0.1500.95 of this writing), this is what I see:

HTML 5 input types rendered in Twitter Bootstrap

The keen-eyed of you will notice that's two columns, not one. And, no, TWB didn't help me there (although it could have). I actually created the screenshot in that manner purely for the illustrations in this book.

If you try the code in Code Sample 15 in different browsers, you'll get different mileage depending on which browser you use. You'll also notice, especially on the mobile browsers, that some of them will adapt the onscreen keyboard or input system to reflect the input type being used.

You should also notice that, if you attempt to break the validation rules in the input types (such as entering letters in the number input, or an incorrectly formatted URL or email in the appropriate field types), the validation state colors as shown previously will take effect, even before you attempt to submit the form.

Aside from the standard input types, using the correct form for grouping classes and marking up your forms correctly, there is still one thing that always seems to be difficult to do: aligning label names with check boxes and radio buttons.

By wrapping your check boxes and radio buttons actually inside a label element as follows:

<label class="checkbox">

  <input type="checkbox" value="">

  This is my option

</label>

And adding the class of "checkbox" or "radio" to the label as required, Twitter Bootstrap will line the label up with the control so you never again have to worry about whether or not the layout of your options panels looks correct.

If you further add the inline optional class, you'll get your check boxes and radio buttons to all appear inline on the same row horizontally:

<label class="checkbox inline">

  <input type="checkbox" value="">

  A

</label>

<label class="checkbox inline">

  <input type="checkbox" value="">

  B

</label>

<label class="checkbox inline">

  <input type="checkbox" value="">

  C

</label>

This will produce the following output:

Inline check boxes

You can add the "inline" optional class to radio buttons in the same manner.

The rest of the input types—such as Select and Options and Select with an attribute of multiple—will also be styled to match other Twitter components and, as such, can also be used with the different span classes and validation styles, just like everything else. Unfortunately, the humble file upload control is not yet subject to the same functionality.

There are some add-on components that allow you to use a file select control and have its visual appearance look like the rest of Bootstrap. But these are largely just text boxes with extended control sets; the actual file control is hidden behind the scenes using a technique I wrote about a few years ago on my blog. The reason for this is, because of security fears, file controls don't have the same freedom of styling and JavaScript operation that other controls have. And this is to be expected, as you wouldn't want a script being able to steal files from your PC, now would you?

Extended Form Controls

There's another good reason to correctly structure your HTML 5 code when using Twitter Bootstrap, and that's so you can take advantage of the extended controls that it makes available.

An extended control is a control where you have a text label that appears to be part of the control, such as an @ sign for a Twitter name input or two decimal points after a number input, as shown in the following image:

Extended input types

Creating these is incredibly easy; you can reproduce the above two examples using the following HTML:

<div class="input-prepend">

  <span class="add-on">@</span>

  <input class="span2" id="prependedInput" type="text" placeholder="Username">

</div>

<div class="input-append">

  <input class="span2" id="appendedInput" type="text">

  <span class="add-on">.00</span>

</div>

As you can see, it's as simple as wrapping the control and its pre- or post-appended part in a standard "<div>" with the class type of "input-prepend" or "input-append" depending on which end of the input control you want to add your extension to.

You can also add a class containing both, and then put a span at either side of the input control, allowing you to add an extension on both ends at the same time.

Text is not the only thing you can extend a control with either. Many of Twitter Bootstrap's components can be used in the same way. For example, the following code:

<div class="input-append">

  <input class="span2" id="appendedInputButton" type="url">

  <button class="btn" type="button">Browse URL</button>

</div>

This will create an HTML 5 URL input control with an attached browse button that looks like the following:

Twitter Bootstrap extended input control with button

The validation states continue to work as expected:

Twitter Bootstrap extended input control with button, showing an error in validation

You can add multiple buttons, segmented buttons with dropdown menus, styled search inputs that look like the premade search form you saw earlier, and all sorts of other additions to make your input fields really stand out.

Other classes that can be added to individual inputs are things such as "uneditable-input" and "disabled." Use both of these together on a span that holds a value from a form to display that data in a form group and style it just like any other form input. The result is not actually an input control but rather an element that has the same visual appearance but does not take part in form submission. The idea is that it can be used to display a record number in a database app but allow that record number to remain unedited and be submitted as a hidden parameter when the form is posted back to the web server.

We also have help text classes as you saw previously in the validation states example. Help text can take one of two classes:

  • help-inline: Attempts to keep the text in line with its control.
  • help-block: Breaks the help text out into a paragraph, starting on a new line but still attempts to keep the text left-aligned with the form controls.

Control Sizing

The final thing I'd like to cover before we finish this chapter on forms is how to use the control sizing features.

It will come as no surprise that the standard spanX classes in the base scaffolding can be used and apply to inputs just as they apply to any other class or element in the framework. Twitter Bootstrap, however, has some additional tricks up its sleeve for input fields.

First off, we can make any input a block-level input. When we do this, the control will expand to fill one row of its entire parent container. Consider the following example of HTML code:

<div class="container-fluid">

  <div class="row-fluid">

    <h1>Twitter Bootstrap</h1>

    <h3>Control Sizing Example</h3>

    <span class="span5">

      <form>

        <input type="text">

      </form>

    </span>

    <span class="span5">

      <h1> This is span 2</h1>

    </span>

  </div>

</div>

And a style tag just to show where those span5s are (just as we did back at the beginning in the chapter on scaffolding):

<style>

  .span5

  {

    background-color: green;

  }

</style>

Then, when you save and render the page in the browser, you should see the following:

Control sizing example 1

As you can see, the input element is tucked right up in the top corner of our span element. You could fiddle with the various offsetX and spanX classes to get the sizing correct, or you can simply add the class input-block-level to your input element like so:

<input type="text" class="input-block-level">

The result should be something like this:

Control sizing example 1 with block-level optional class set

You need to take care of the vertical padding, etc., yourself but, as you can see, you don't need to worry about the input—just the container it’s in—and it will then size itself appropriately.

As previously mentioned, grid sizing can use the spanX classes directly on an input element, but instead of using the row class, TWB provides an extra class specifically for this purpose. This is the controls-row class.

This should be used wherever you would use a row class (as shown in the scaffolding chapter) but where the rows will be housing input controls primarily.

Anywhere you would reasonably expect to have a class of "controls" (see the control groups and validation state examples), you can also expect that to be a normal point in the document where you might want to use a "controls-row" class.

As an example:

<div class="controls controls-row">

  <input class="span4" type="text" placeholder=".span4">

  <input class="span1" type="text" placeholder=".span1">

</div>

When the previous code is rendered, it should give the following:

If you don't want to use the fixed grid, you can also use a relative size grid. In some ways, this is similar to the fluid layout items we saw previously but it's designed specifically for laying out your form controls.

Start a new template document, and then add the following body code to it:

<div class="container-fluid">

  <div class="row-fluid">

    <h1>Twitter Bootstrap</h1>

    <h3>Relative Sizing Example</h3>

  </div>

  <div class="row-fluid">

    <span class="span5">

      <form>

      <input class="input-mini" type="text" placeholder=".input-mini"><br />

      <input class="input-small" type="text" placeholder=".input-small"><br />

      <input class="input-medium" type="text" placeholder=".input-medium"><br />

      <input class="input-large" type="text" placeholder=".input-large"><br />

      <input class="input-xlarge" type="text" placeholder=".input-xlarge"><br />

      <input class="input-xxlarge" type="text" placeholder=".input-xxlarge"><br />

      <input class="input-block-level" type="text" placeholder=".input-block-level (for   comparison)"><br />

    </form>

  </span>

</div>

</div>

Code Sample 17: Relative sizing

If you save and render this with a style rule to show color behind the span5 class (green in my case), you should see something like the following:

Twitter Bootstrap relative sizing example

Notice I've also added a block size class to one of the elements, just to compare things.

If you now start playing with the span5 on the parent span holding the controls, you should see that each of them always maintains a relative size to the container holding the elements, once again making sure that you don't need masses of nested classes to control the layout and balance of your forms.

There are a couple more minor things that are present in the forms section such as the "form-actions" class which, when used with a correctly laid out form, will ensure that control buttons and other similar things remain lined up with their parent form controls.

In this chapter, we saw one of the most impressive aspects of Twitter Bootstrap; however, some of the more astute among you may be wondering where the buttons and such are. That is the subject of the next chapter.

Scroll To Top
Disclaimer
DISCLAIMER: Web reader is currently in beta. Please report any issues through our support system. PDF and Kindle format files are also available for download.

Previous

Next



You are one step away from downloading ebooks from the Succinctly® series premier collection!
A confirmation has been sent to your email address. Please check and confirm your email subscription to complete the download.