Bootstrap - Forms

Creating Basic Forms

To create a basic form in Bootstrap, you need to understand the structure and components that make up a form. Bootstrap provides classes and conventions to help you build forms quickly and consistently.

First, wrap your form elements inside a <form> tag. This tag serves as a container for all the form controls and provides a logical grouping for the form. Inside the <form> tag, you can use HTML elements such as <input>, <textarea>, <select>, and <button> to create different types of form controls.

Example: Form structure

<form>
    <input type="text" class="form-control" id="exampleInput">
    <textarea class="form-control" id="exampleTextarea"></textarea>
    <select class="form-control" id="exampleSelect">
        <option>Option 1</option>
        <option>Option 2</option>
    </select>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>

Next, use form groups to organize and provide proper spacing between form controls. Create a form group by wrapping a form control and its label inside a <div> element with the class form-group. This keeps the form controls and labels together and provides consistent spacing between them.

Example: Form group structure

<div class="form-group">
    <label for="exampleInput">Input Label</label>
    <input type="text" class="form-control" id="exampleInput">
</div>
<div class="form-group">
    <label for="exampleTextarea">Textarea Label</label>
    <textarea class="form-control" id="exampleTextarea"></textarea>
</div>

Form controls are the interactive elements that allow users to input data into the form. Bootstrap supports a wide range of form controls:

Form Control Description
Text inputs Single-line text fields
Textareas Multi-line text fields
Checkboxes Allows selecting multiple options
Radio buttons Allows selecting a single option
Select dropdowns Provides a dropdown list of options
File inputs Allows file uploads

To style form controls, Bootstrap provides classes such as form-control for text-based inputs and custom-control for custom checkboxes and radio buttons.

Example: Styled form controls

<input type="text" class="form-control" id="exampleInput">
<input type="checkbox" class="custom-control-input" id="exampleCheckbox">
<label class="custom-control-label" for="exampleCheckbox">Check this</label>

Form labels provide a description or prompt for each form control. Associate a label with a form control using the for attribute on the <label> element. The value of for should match the id attribute of the corresponding form control. This establishes a logical connection between the label and the control.

Example: Form label association

<label for="exampleTextarea">Textarea Label</label>
<textarea class="form-control" id="exampleTextarea"></textarea>

Bootstrap offers various form layout options to arrange form controls and labels:

Layout Description
Vertical Form controls and labels are stacked vertically
Horizontal Labels and controls are aligned side by side
Inline Form controls are displayed in a single line

Use the form-group class for vertical layouts, form-horizontal for horizontal layouts, and form-inline for inline layouts.

By utilizing these form elements and layout options, you can create structured and well-organized forms in Bootstrap. Use appropriate form controls, associate labels with controls, and choose a suitable form layout based on your design requirements.

Form Control Types

Bootstrap provides form control types to handle different input needs. Here are the commonly used form control types in Bootstrap.

Text Inputs

Text inputs are for entering single-line text data. To create a text input, use the <input> element with the type attribute set to "text" and add the class "form-control" to apply Bootstrap's styling.

Text Input Example

<input type="text" class="form-control" placeholder="Enter your name">

Textareas

Textareas are for entering multi-line text data. To create a textarea, use the <textarea> element and add the class "form-control" to apply Bootstrap's styling.

Textarea Example

<textarea class="form-control" rows="3" placeholder="Enter your message"></textarea>

Checkboxes

Checkboxes let users select one or more options from a list. To create a checkbox, use the <input> element with the type attribute set to "checkbox" and add the class "form-check-input" to apply Bootstrap's styling. Wrap the checkbox input and its label inside a <div> element with the class "form-check".

Checkbox Example

<div class="form-check">
  <input class="form-check-input" type="checkbox" id="checkbox1">
  <label class="form-check-label" for="checkbox1">Option 1</label>
</div>

Radio Buttons

Radio buttons let users select a single option from a list. To create a radio button, use the <input> element with the type attribute set to "radio" and add the class "form-check-input" to apply Bootstrap's styling. Wrap the radio input and its label inside a <div> element with the class "form-check".

Radio Button Example

<div class="form-check">
  <input class="form-check-input" type="radio" name="radioOptions" id="radio1">
  <label class="form-check-label" for="radio1">Option 1</label>
</div>

Select Dropdowns

Select dropdowns let users choose an option from a list of predefined values. To create a select dropdown, use the <select> element and add the class "form-control" to apply Bootstrap's styling. Each option is defined using the <option> element.

Select Dropdown Example

<select class="form-control">
  <option>Option 1</option>
  <option>Option 2</option>
  <option>Option 3</option>
</select>

File Inputs

File inputs let users select and upload files from their device. To create a file input, use the <input> element with the type attribute set to "file" and add the class "form-control-file" to apply Bootstrap's styling.

File Input Example

<input type="file" class="form-control-file">

Range Inputs

Range inputs let users select a value from a specified range. To create a range input, use the <input> element with the type attribute set to "range" and add the class "form-control-range" to apply Bootstrap's styling.

Range Input Example

<input type="range" class="form-control-range">

These are the commonly used form control types in Bootstrap. Each control type has its own purpose and can be customized with additional attributes and classes to fit your specific needs.

Form Layouts

Bootstrap has several form layout options to arrange form controls and labels in different ways. The most common form layouts in Bootstrap are vertical, horizontal, inline, and grid-based layouts. Here is each of these layouts in detail.

Vertical Form Layout

The vertical form layout is the default layout in Bootstrap. In this layout, form controls and labels are stacked vertically, one below the other. Each form control is placed in a separate row, making the form appear longer vertically.

To create a vertical form layout, wrap each form control and its label inside a <div> element with the class "form-group". This creates a logical grouping and provides proper spacing between the form controls.

Example: Vertical Form Layout

<form>
  <div class="form-group">
    <label for="name">Name</label>
    <input type="text" class="form-control" id="name" placeholder="Enter your name">
  </div>
  <div class="form-group">
    <label for="email">Email</label>
    <input type="email" class="form-control" id="email" placeholder="Enter your email">
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

Horizontal Form Layout

The horizontal form layout aligns form controls and labels side by side, creating a more compact and readable layout. In this layout, labels are placed to the left of the form controls, and the controls are aligned horizontally.

To create a horizontal form layout, add the class "form-horizontal" to the <form> element. Then, wrap each form control and its label inside a <div> element with the class "form-group row". The label should have the class "col-form-label" and be placed inside a <div> with the appropriate column class (e.g., "col-sm-2"). The form control should be placed inside another <div> with the remaining column class (e.g., "col-sm-10").

Example: Horizontal Form Layout

<form class="form-horizontal">
  <div class="form-group row">
    <label for="name" class="col-sm-2 col-form-label">Name</label>
    <div class="col-sm-10">
      <input type="text" class="form-control" id="name" placeholder="Enter your name">
    </div>
  </div>
  <div class="form-group row">
    <label for="email" class="col-sm-2 col-form-label">Email</label>
    <div class="col-sm-10">
      <input type="email" class="form-control" id="email" placeholder="Enter your email">
    </div>
  </div>
  <div class="form-group row">
    <div class="col-sm-offset-2 col-sm-10">
      <button type="submit" class="btn btn-primary">Submit</button>
    </div>
  </div>
</form>

Inline Form Layout

The inline form layout displays form controls in a single line, making it suitable for simple forms or search bars. In this layout, form controls are placed next to each other horizontally, without labels.

To create an inline form layout, add the class "form-inline" to the <form> element. Each form control should have the class "form-control" to maintain proper styling.

Example: Inline Form Layout

<form class="form-inline">
  <input type="text" class="form-control" placeholder="Enter your name">
  <input type="email" class="form-control" placeholder="Enter your email">
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

Grid-based Form Layout

Bootstrap's grid system can also be used to create custom form layouts. By using the grid classes, you can create complex form layouts with multiple columns and varying widths.

To create a grid-based form layout, use the "row" and "col-*" classes to define the structure of your form. Each form control and its label should be placed inside a <div> element with the appropriate column class.

Example: Grid-based Form Layout

<form>
  <div class="row">
    <div class="col-sm-6">
      <div class="form-group">
        <label for="firstName">First Name</label>
        <input type="text" class="form-control" id="firstName" placeholder="Enter your first name">
      </div>
    </div>
    <div class="col-sm-6">
      <div class="form-group">
        <label for="lastName">Last Name</label>
        <input type="text" class="form-control" id="lastName" placeholder="Enter your last name">
      </div>
    </div>
  </div>
  <div class="row">
    <div class="col-sm-12">
      <div class="form-group">
        <label for="email">Email</label>
        <input type="email" class="form-control" id="email" placeholder="Enter your email">
      </div>
    </div>
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

Form Validation

Form validation is an important part of handling user input and making sure data is correct. Bootstrap has classes and styles for client-side form validation, making it easy to give feedback to users about their input.

Client-side Validation with Bootstrap

Bootstrap supports client-side form validation by using HTML5 validation attributes and its own validation classes. To use Bootstrap's validation styles, add the "needs-validation" class to the <form> element. Then, add the "required" attribute to the form controls that are required fields.

Example: Client-side Validation

<form class="needs-validation" novalidate>
  <div class="form-group">
    <label for="name">Name</label>
    <input type="text" class="form-control" id="name" placeholder="Enter your name" required>
    <div class="invalid-feedback">Please provide a name.</div>
  </div>
  <div class="form-group">
    <label for="email">Email</label>
    <input type="email" class="form-control" id="email" placeholder="Enter your email" required>
    <div class="invalid-feedback">Please provide a valid email.</div>
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

Validation Classes

Bootstrap has validation classes that can be added to form controls to show their validation state. The main validation classes are:

Class Description
"is-valid" Shows a valid input value.
"is-invalid" Shows an invalid input value.

These classes can be added to form controls dynamically based on the validation state. When a form control has the "is-invalid" class, Bootstrap uses a red border color and shows an error message.

Example: Validation Classes

<div class="form-group">
  <label for="username">Username</label>
  <input type="text" class="form-control is-valid" id="username" required>
</div>
<div class="form-group">
  <label for="password">Password</label>
  <input type="password" class="form-control is-invalid" id="password" required>
  <div class="invalid-feedback">Please provide a password.</div>
</div>

Validation Feedback

Bootstrap lets you show validation feedback messages to users. The feedback messages can be shown below the form controls using the "valid-feedback" and "invalid-feedback" classes.

To show validation feedback, create a <div> element with the right feedback class ("valid-feedback" for valid input or "invalid-feedback" for invalid input) and put it after the form control.

Example: Validation Feedback

<div class="form-group">
  <label for="email">Email</label>
  <input type="email" class="form-control" id="email" required>
  <div class="valid-feedback">Looks good!</div>
  <div class="invalid-feedback">Please provide a valid email.</div>
</div>

Custom Validation Styles

Along with the default validation styles, Bootstrap lets you change the validation look using CSS. You can change the colors, borders, and other styles of the validation classes to match your application's design.

To change the validation styles, target the .is-valid and .is-invalid classes in your CSS and use your desired styles.

Example: Custom Validation Styles

.form-control.is-valid {
  border-color: #28a745;
}

.form-control.is-invalid {
  border-color: #dc3545;
}

.valid-feedback {
  color: #28a745;
}

.invalid-feedback {
  color: #dc3545;
}

By using Bootstrap's form validation classes and giving the right validation feedback, you can help users enter valid data and make your forms easier to use.

Form Customization

Bootstrap provides default styles for form controls, but you may want to customize the form appearance to match your application's design or branding. Bootstrap lets you customize form control styles, apply custom CSS to forms, and override the default form styles.

Customizing Form Control Styles

Bootstrap provides CSS classes to style form controls. However, you can also customize the form control appearance by modifying their styles directly or by creating custom CSS classes.

Example: Customizing form control styles

.form-control {
  background-color: #f8f9fa;
  border-color: #ced4da;
  padding: 0.5rem 1rem;
  font-size: 1rem;
}

.form-control:focus {
  border-color: #80bdff;
  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}

In the above example, the .form-control class is targeted to change the background color, border color, padding, and font size of form controls. The :focus pseudo-class is used to style the form control when it receives focus, changing the border color and adding a box shadow.

Applying Custom CSS to Forms

You can also apply custom CSS to the entire form or specific form sections. This lets you create a consistent and cohesive design for your forms.

To apply custom CSS to forms, create a custom CSS class and apply it to the <form> element or any parent element of the form controls. Then, define the styles for that class in your CSS.

Example: Applying custom CSS to a form

<form class="custom-form">
  ...
</form>
.custom-form {
  background-color: #f8f9fa;
  padding: 2rem;
  border-radius: 0.5rem;
}

.custom-form .form-group {
  margin-bottom: 1.5rem;
}

.custom-form .form-control {
  border-radius: 0.25rem;
}

Overriding Bootstrap Form Styles

Sometimes, you may need to override the default Bootstrap form styles to achieve a specific design or to resolve conflicts with your custom styles. Bootstrap lets you override its form styles by using more specific selectors or by increasing the specificity of your custom styles.

To override Bootstrap form styles, use more specific selectors in your CSS.

Example: Overriding Bootstrap form styles

.my-form .form-control {
  border-color: #ff0000;
}

.my-form .btn-primary {
  background-color: #00ff00;
  border-color: #00ff00;
}

In this example, the .my-form class is used as a more specific selector to target form controls and buttons within a specific form. The border color of form controls and the background color and border color of the primary button are overridden.

Form Accessibility

When creating forms, it's important to make them accessible to all users, including those with disabilities. Bootstrap provides features and best practices to help you create accessible forms.

Labeling Form Controls

One of the most important aspects of form accessibility is properly labeling form controls. Each form control should have a label that clearly indicates its purpose. In Bootstrap, you can use the <label> element to associate a label with a form control.

Example: Labeling form controls

<div class="form-group">
  <label for="name">Name</label>
  <input type="text" class="form-control" id="name" placeholder="Enter your name">
</div>

By using the for attribute on the <label> element and matching it with the id attribute of the form control, you create a logical connection between the label and the control. This helps screen readers and other assistive technologies understand the relationship between the label and the control.

Providing Instructions and Error Messages

In addition to labeling form controls, it's important to provide clear instructions and error messages to guide users in completing the form correctly. Bootstrap has classes and elements that you can use to display instructions and error messages.

To provide instructions or additional information about a form control, you can use the <small> element with the class "form-text".

Example: Providing instructions

<div class="form-group">
  <label for="password">Password</label>
  <input type="password" class="form-control" id="password">
  <small class="form-text text-muted">Must be at least 8 characters long.</small>
</div>

For error messages, you can use the "invalid-feedback" class to display validation feedback when a form control is invalid.

Example: Displaying error messages

<div class="form-group">
  <label for="email">Email</label>
  <input type="email" class="form-control is-invalid" id="email">
  <div class="invalid-feedback">Please provide a valid email address.</div>
</div>

Keyboard Navigation

Ensuring that forms are keyboard accessible is important for users who rely on keyboard navigation. Bootstrap forms are designed to be keyboard-friendly by default. Form controls can be navigated using the Tab key, and buttons can be activated using the Enter or Space key.

To further enhance keyboard accessibility, you can use the tabindex attribute to define a custom tab order for form controls. This is useful when you have a complex form layout or want to guide users through a specific sequence of form controls.

Example: Enhancing keyboard accessibility

<form>
  <div class="form-group">
    <label for="name">Name</label>
    <input type="text" class="form-control" id="name" tabindex="1">
  </div>
  <div class="form-group">
    <label for="email">Email</label>
    <input type="email" class="form-control" id="email" tabindex="2">
  </div>
  <button type="submit" class="btn btn-primary" tabindex="3">Submit</button>
</form>

ARIA Attributes for Forms

ARIA (Accessible Rich Internet Applications) attributes provide additional semantic information to assistive technologies about the purpose and state of form controls. Bootstrap supports the use of ARIA attributes to enhance form accessibility.

Some common ARIA attributes used in forms include:

Attribute Description
aria-label Provides a label for a form control.
aria-describedby Indicates the ID of an element that describes the control.
aria-invalid Indicates that a form control's value is invalid.
aria-required Indicates that a form control is required.

Example: Using ARIA attributes

<div class="form-group">
  <label for="username">Username</label>
  <input type="text" class="form-control" id="username" aria-describedby="usernameHelp" required aria-required="true">
  <small id="usernameHelp" class="form-text text-muted">Enter your unique username.</small>
</div>

The aria-describedby attribute is used to associate the helper text with the form control, providing additional context to assistive technologies. The aria-required attribute indicates that the control is required.

Integrating Forms with Back-end

Integrating forms with the back-end is an important part of web development. It lets you handle form submissions, send form data to the server, and process the data on the server-side. Bootstrap provides a foundation for creating forms, but the integration with the back-end needs more steps.

Handling Form Submissions

When a user fills out a form and clicks the submit button, the form data needs to be sent to the server for processing. To handle form submissions, you need to specify the HTTP method and the URL where the form data should be sent.

You can use the action attribute of the <form> element to specify the URL that will handle the form submission. The method attribute determines the HTTP method used for the form submission, such as GET or POST.

Example: HTML Form Handling

<form action="/submit-form" method="POST">
  <div class="form-group">
    <label for="name">Name</label>
    <input type="text" class="form-control" id="name" name="name" required>
  </div>
  <div class="form-group">
    <label for="email">Email</label>
    <input type="email" class="form-control" id="email" name="email" required>
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

Sending Form Data to the Server

When a form is submitted, the form data is sent to the server as key-value pairs. Each form control's name attribute acts as the key, and its value becomes the value.

To make sure the form data is sent to the server, assign unique and meaningful name attributes to each form control.

Example: Form Control Names

<div class="form-group">
  <label for="username">Username</label>
  <input type="text" class="form-control" id="username" name="username" required>
</div>
<div class="form-group">
  <label for="password">Password</label>
  <input type="password" class="form-control" id="password" name="password" required>
</div>

Processing Form Data on the Server-side

Once the form data is sent to the server, it needs to be processed and handled based on your application's needs. The server-side code, written in languages like PHP, Ruby, Python, or Node.js, receives the form data and does the needed operations.

The server-side code can get the form data by accessing the keys based on the name attributes of the form controls. It can then validate the data, store it in a database, send emails, or do any other needed actions.

Example: PHP Form Processing

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $name = $_POST["name"];
  $email = $_POST["email"];

  // Process the form data (e.g., store in a database, send an email, etc.)
  // ...

  // Redirect or display a success message
  header("Location: success.php");
  exit();
}
?>

Remember to always validate and clean user input on the server-side to prevent security issues like SQL injection or cross-site scripting (XSS) attacks.

By handling form submissions, sending form data to the server, and processing the data on the server-side, you can create interactive and dynamic web applications that capture and use user input.

Form Plugins and Extensions

Bootstrap provides a foundation for creating forms, but sometimes you may need more functionality or advanced features. There are many form plugins and extensions that work with Bootstrap to improve your forms. Here are some popular form plugins and extensions:

Date and Time Pickers

Date and time pickers let users easily select a date or time using a user-friendly interface. They provide an intuitive way to input date and time values compared to typing.

One popular date and time picker plugin for Bootstrap is the Bootstrap Datepicker. It offers a customizable and responsive date picker widget that works with Bootstrap forms.

Example: Bootstrap Datepicker

<div class="form-group">
  <label for="datepicker">Select Date</label>
  <input type="text" class="form-control" id="datepicker">
</div>
$(document).ready(function() {
  $('#datepicker').datepicker();
});

Color Pickers

Color pickers let users select a color from a palette or by entering a specific color value. They are used in forms where color selection is needed, such as in design or customization settings.

One popular color picker plugin for Bootstrap is Bootstrap Colorpicker. It provides a color picker widget that can be easily added to Bootstrap forms.

Example: Bootstrap Colorpicker

<div class="form-group">
  <label for="colorpicker">Select Color</label>
  <input type="text" class="form-control" id="colorpicker">
</div>
$(document).ready(function() {
  $('#colorpicker').colorpicker();
});

Autocomplete and Typeahead

Autocomplete and typeahead functionality lets users quickly find and select options from a predefined list as they type. It provides suggestions based on the user's input, making it easier to fill out forms with known values.

One popular autocomplete and typeahead plugin for Bootstrap is Bootstrap Typeahead. It offers a simple and customizable typeahead functionality that can be added to Bootstrap forms.

Example: Bootstrap Typeahead

<div class="form-group">
  <label for="typeahead">Select Country</label>
  <input type="text" class="form-control" id="typeahead" data-provide="typeahead">
</div>
$(document).ready(function() {
  var countries = ['United States', 'Canada', 'United Kingdom', 'Australia', 'Germany'];
  $('#typeahead').typeahead({
    source: countries
  });
});

Masked Input Fields

Masked input fields format user input based on a predefined pattern. They are useful when you need to enforce a specific format for input values, such as phone numbers, dates, or credit card numbers.

One popular masked input plugin for Bootstrap is jQuery Mask Plugin. It lets you define input masks using a simple syntax and automatically formats the user's input as they type.

Example: jQuery Mask Plugin

<div class="form-group">
  <label for="phone">Phone Number</label>
  <input type="text" class="form-control" id="phone">
</div>
$(document).ready(function() {
  $('#phone').mask('(000) 000-0000');
});

Advanced Validation Plugins

While Bootstrap provides basic form validation classes, you may need more advanced validation capabilities. Advanced validation plugins offer features like real-time validation, custom validation rules, and error message handling.

One popular advanced validation plugin for Bootstrap is jQuery Validation Plugin. It provides a set of validation methods and lets you define custom validation rules and error messages.

Example: jQuery Validation Plugin

<form id="myForm">
  <div class="form-group">
    <label for="email">Email</label>
    <input type="email" class="form-control" id="email" name="email" required>
  </div>
  <div class="form-group">
    <label for="password">Password</label>
    <input type="password" class="form-control" id="password" name="password" required>
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
</form>
$(document).ready(function() {
  $('#myForm').validate({
    rules: {
      email: {
        required: true,
        email: true
      },
      password: {
        required: true,
        minlength: 6
      }
    },
    messages: {
      email: {
        required: 'Please enter your email',
        email: 'Please enter a valid email address'
      },
      password: {
        required: 'Please enter your password',
        minlength: 'Your password must be at least 6 characters long'
      }
    }
  });
});

These form plugins and extensions improve the functionality and user experience of Bootstrap forms. They provide extra features and interactivity, making it easier to create advanced and user-friendly forms.