Type to generate UI components from text

OR

Browse thousands of MUI, Tailwind, React components that are fully customizable and responsive.

Explore Components

Bootstrap Form: Complete Guide to Creating Forms in Bootstrap

Do you want to create a stylish and responsive form for your web application using Bootstrap? Forms are an important way to interact with users on your website.

Bootstrap provides form control components that you can add to your project to easily style your web forms.

In this tutorial, we’ll cover all there is to know about creating responsive forms with Bootstrap. Before we begin, let’s briefly understand what Bootstrap is and the importance of web forms.

Introduction to Bootstrap Forms

Bootstrap is a framework designed to assist developers in creating responsive and visually appealing websites with ease. Think of Bootstrap as a comprehensive toolkit that provides a variety of ready-to-use components.

This includes CSS and JavaScript elements that are essential for modern web design. The framework is favored for its responsiveness, ensuring websites are mobile-friendly and adjustable across various devices.

It simplifies the web development process, allowing developers to focus on functionality without compromising on aesthetics.

Speaking of simplifying development, PureCode provides a list of 10k AI-generated templates to speed up your workflow. Our templates include form components to help you quickly create forms for your website.

Get Started With PureCode

Importance of Forms in Web Design

Web forms are the primary method of gathering user input, required for tasks such as user registration, data collection, feedback submission, and online transactions.

The design and usability of forms significantly impact user experience. Well-designed forms improve user engagement and contribute to the overall effectiveness of a website. They need to be intuitive, accessible, and visually integrated into the site’s design. This is where Bootstrap’s form components become valuable, offering a balance between aesthetics and functionality.

Bootstrap Forms and Their Responsiveness

Bootstrap forms stand out for their responsiveness and ease of integration. With Bootstrap, forms are automatically styled with a professional look and feel. These forms are responsive by design, meaning they adapt seamlessly to different screen sizes and resolutions.

The framework offers various form controls, including input fields, checkboxes, radio buttons, and more. The responsiveness of Bootstrap forms ensures that they remain functional and visually appealing, regardless of the viewing context. This adaptability is essential for creating inclusive web experiences that cater to all users, regardless of their device preferences.

Setting Up Bootstrap for Forms

Integrating Bootstrap into your project is the first step toward using its full potential for creating responsive and attractive forms.

Including Bootstrap in Your Project

To start using Bootstrap in your project, you need to include it. There are mainly two ways to do this:

  1. Using a Content Delivery Network (CDN): This is the simplest method. You include links to Bootstrap’s CSS and JS files in your HTML file’s head section. It looks something like this:

    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    
    <!-- jQuery library -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    
    <!-- Popper JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    
    <!-- Latest compiled JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
  2. Downloading and Hosting Locally: Alternatively, you can download Bootstrap and include the files directly in your project. This is a good choice if you want to customize Bootstrap’s components at a deeper level or if you prefer to have everything hosted within your project.

Basic Structure of a Bootstrap Form

Once Bootstrap is included in your project, you can start building your form. Here’s the basic structure of a Bootstrap form:

1. Form Tag: Start with the <form> element. This is standard HTML, but you’ll be adding Bootstrap classes for styling.

2. Form Groups: Inside the form, use the .form-group class to ensure proper spacing of labels and form controls.

<form>
  <div class="form-group">
    <!-- Label and input elements go here -->
  </div>
</form>

3. Labels and Inputs: Include a <label> and an <input> element for each field in your form. Bootstrap enhances these with classes like .form-control for inputs. This class applies styling and ensures responsive behavior.

<div class="form-group">
  <label for="email">Email address:</label>
  <input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
</div>

4. Buttons: Finally, add a submit button. Bootstrap’s .btn classes can be used here to style the button.

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

Putting it all together, here’s what we come up with.

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

Bootstrap forms are highly customizable, allowing you to add various form elements like checkboxes, radio buttons, select menus, and more. Each of these elements comes with its own specific Bootstrap classes for enhanced styling and functionality.

Types of Forms in Bootstrap

Bootstrap also offers various types of form layouts to cater to different design needs. So let’s explore these types, namely Inline Forms, Horizontal Forms, and Vertical Forms.

1. Inline Forms

Inline Forms in Bootstrap are designed for situations where you want to display form controls in a single line. This type of form is ideal for creating compact forms, often used for search bars or quick login fields. Here’s how you can create an Inline Form:

    <form class="row row-cols-lg-auto g-3 align-items-center my-4">
      <div class="col-12">
        <label for="email" class="mr-sm-2">Email:</label>
        <input type="email" class="form-control mb-2 mr-sm-2" id="email" placeholder="Enter email">
      </div>
  
      <div class="col-12">
        <label for="pwd" class="mr-sm-2">Password:</label>
        <input type="password" class="form-control mb-2 mr-sm-2" id="pwd" placeholder="Enter password">  
      </div>
  
      <div class="col-12">
        <button type="submit" class="btn btn-primary">Submit</button>
      </div>
    </form>

In this example, the row-cols-lg-auto class is used to align the form controls and labels side by side.

2. Horizontal Forms

Horizontal Forms are used when you want to align form labels and controls in the same row but in a more structured and aligned manner. This layout is often used for detailed forms where a clear separation between the label and the control is needed.

Example of a Horizontal Form:

<form class=" col-6 mx-auto">
  <div class="form-group row">
    <label for="inputEmail3" class="col-sm-2 col-form-label">Email</label>
    <div class="col-sm-10">
      <input type="email" class="form-control" id="inputEmail3" placeholder="Email">
    </div>
  </div>
  <div class="form-group row my-3">
    <label for="inputPassword3" class="col-sm-2 col-form-label">Password</label>
    <div class="col-sm-10">
      <input type="password" class="form-control" id="inputPassword3" placeholder="Password">
    </div>
  </div>
  <div class="form-group row">
    <div class="col-sm-12">
      <button type="submit" class="btn btn-primary btn-block">Sign in</button>
    </div>
  </div>
</form>

In this code, the row class and grid system are used to align labels and fields horizontally.

3. Vertical Forms

Vertical Forms are the default style in Bootstrap and are the most common form layouts used in various applications. In this layout, each label and control is stacked on top of one another.

Here’s a simple Vertical Form example:

<form class="mx-auto col-6">
  <div class="form-group mt-3">
    <label for="email">Email address:</label>
    <input type="email" class="form-control" id="email" placeholder="Enter email">
  </div>
  <div class="form-group my-3">
    <label for="pwd">Password:</label>
    <input type="password" class="form-control" id="pwd" placeholder="Enter password">
  </div>
  <button type="submit" class="btn btn-primary btn-block">Submit</button>
</form>

The vertical form is straightforward, where the form-group class is used to maintain optimal spacing around the form elements.

Each of these form types serves different design and usability purposes, and Bootstrap makes it easy to implement them with its pre-defined classes and grid system.

Form Controls

Bootstrap’s form controls are like the building blocks for creating interactive and user-friendly web forms. So let’s overview Bootstrap’s form controls (the key ones): Input Types, Textarea, Checkboxes and Radios, and Select Options.

1. Input Types (text, email, password, etc.)

Bootstrap enhances standard HTML input types with styles and functionalities. These include text, email, password, and more. Each input type is used for collecting different kinds of user data.

Example of various input types in Bootstrap:

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

  <!-- Email input -->
  <div class="form-group">
    <label for="email">Email:</label>
    <input type="email" class="form-control" id="email" placeholder="Enter email">
  </div>

  <!-- Password input -->
  <div class="form-group">
    <label for="pwd">Password:</label>
    <input type="password" class="form-control" id="pwd" placeholder="Enter password">
  </div>
</form>

In each case, the form-control class is used to style the inputs consistently.

2. Textarea

A textarea is used for multi-line text input, such as comments or messages. Thus, Bootstrap’s styling for textareas ensures they are visually consistent with other form controls.

Textarea example:

<div class="form-group">
  <label for="comment">Comment:</label>
  <textarea class="form-control" rows="5" id="comment" placeholder="Enter your comment"></textarea>
</div>

3. Checkboxes and Radios

Checkboxes and radio buttons are used for selecting one or more options from a set. Bootstrap styles these controls for better usability and appearance.

Checkbox and radio button examples:

<!-- Checkboxes -->
<div class="form-check">
  <input class="form-check-input" type="checkbox" value="" id="defaultCheck1">
  <label class="form-check-label" for="defaultCheck1">
    Check me out
  </label>
</div>

<!-- Radio buttons -->
<div class="form-check">
  <input class="form-check-input" type="radio" name="exampleRadios" id="exampleRadio1" value="option1" checked>
  <label class="form-check-label" for="exampleRadio1">
    First radio
  </label>
</div>

4. Select Options

Select options are dropdown lists that allow users to choose one option from many. Bootstrap styles these to be consistent with other form elements.

Select option example:

<div class="form-group">
  <label for="selectExample">Example Select</label>
  <select class="form-control" id="selectExample">
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
  </select>
</div>

In each of these examples, Bootstrap classes are applied to ensure that the form controls are not only functional but also visually integrated and responsive.

Enhancing Forms with Bootstrap

Bootstrap also includes additional classes to customize the appearance of your form fields. For example, you can make the input field smaller or larger depending on your preference. So here are some additional customization classes to try out.

Adding Form Control Styles

Bootstrap provides various classes to style form controls. There are various form control styles you can consider as well. For example, the form-control-lg and form-control-sm classes adjust the size of the input fields. Here is an example:

<div class="row">
        <div class="col-4">
          <input class="form-control form-control-lg" type="text" placeholder="Large input">
        </div>
        <div class="col-4">
          <input class="form-control" type="text" placeholder="Default input">
        </div>
        <div class="col-4">
          <input class="form-control form-control-sm" type="text" placeholder="Small input">
        </div> 
 </div>

Form Validation States and Messages

Bootstrap includes styles for validation states with feedback messages. This helps in providing immediate contextual feedback to users. Here is an example implementation.

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

You’ll need to use JavaScript to control the state of the input element such that the validation messages show up only when there is an error. To learn more, check out the video below.

Disabled and Read-Only Inputs

These input elements do not allow user input in the field. Although they prevent user interactions, their functionalities differ.

To visually indicate that a form field is not interactive, you can use the disabled attribute on input fields. For read-only inputs, you’ll need to apply the readonly attribute on the input element. Here is an example with both types of input.

<input class="form-control" type="text" placeholder="Disabled input" disabled>
<input class="form-control" type="text" placeholder="Read-Only input" readonly>

The main difference between both of them is that read-only inputs can still be focused and selected, while disabled inputs cannot. Here is a preview of the code example above.

The table below explains the differences between both input types in detail.

AttributeDisabledReadonly
DefinitionIndicates that an input field should be disabledIndicates that an input field should be read-only
StylingThe field appears grayed out with the mouse-hover effect disabled.The field also appears grayed out but allows mouse interaction
ValueWhen an element is disabled, it cannot be interacted with or submitted.When an element is read only, it cannot be edited but can be submitted.

Input Groups and Addons

Input groups wrap input elements with additional text or buttons. This is useful for adding contextual addons to form fields. You can add an element or icon before and after the input field using the prepend and append Bootstrap classes. Here is an example.

<div class="input-group mb-3">
  <input type="text" class="form-control" placeholder="Recipient's username" aria-label="Recipient's username">
  <div class="input-group-append">
    <span class="input-group-text">@example.com</span>
  </div>
</div>
<div class="input-group mb-3">
  <div class="input-group-prepend">
    <span class="input-group-text">@</span>
  </div>
  <input type="text" class="form-control" placeholder="Username">
</div>

In this example, input-group-append adds contextual text to the input field after the element. The input-group-prepend class adds contextual texts or icons before the input element.

Layouts and Grid System in Forms

Bootstrap’s grid system is a powerful tool for creating responsive and structured layouts in web forms. Let’s delve into how you can use this system for form layout and the considerations for responsive form design.

Using the Bootstrap Grid System for Form Layout

Bootstrap’s grid system uses a series of containers, rows, and columns to layout and align content. It’s based on a 12-column structure which can be combined in various ways to create different types of layouts.

Here’s how you can use it in forms:

<form>
  <div class="row">
    <div class="col">
      <input type="text" class="form-control" placeholder="First name">
    </div>
    <div class="col">
      <input type="text" class="form-control" placeholder="Last name">
    </div>
  </div>
</form>

In this example, we divided the form into two columns, each occupying half of the available space. This layout is responsive, meaning it will adjust based on the screen size.

Responsive Form Design Considerations

When designing forms with the Bootstrap grid system, it’s crucial to consider how they will adjust to different screen sizes. Bootstrap’s grid classes (col-xs-, col-sm-, col-md-, col-lg-, col-xl-) allow you to specify how forms should behave on various devices. Here is an example.

<form>
  <div class="row">
    <div class="form-group col-md-6">
      <label for="inputEmail4">Email</label>
      <input type="email" class="form-control" id="inputEmail4" placeholder="Email">
    </div>
    <div class="form-group col-md-6">
      <label for="inputPassword4">Password</label>
      <input type="password" class="form-control" id="inputPassword4" placeholder="Password">
    </div>
  </div>
  <div class="form-group">
    <label for="inputAddress">Address</label>
    <input type="text" class="form-control" id="inputAddress" placeholder="1234 Main St">
  </div>
  <button type="submit" class="btn btn-primary">Sign in</button>
</form>

In this example, the email and password fields are displayed side by side on medium-sized devices and larger (col-md-6). On smaller screens, these fields stack vertically for better readability and usability.

Key Considerations for Responsive Design

  1. Stacking on Smaller Screens: Ensure form elements stack vertically on smaller screens for easy readability and interaction.

  2. Column Sizing: Use different column sizes (col-xs-, col-sm-, etc.) to control how much space each form element occupies on various devices.

  3. Alignment and Spacing: Utilize Bootstrap’s spacing and alignment classes to ensure that your form looks balanced and is easy to use on all screen sizes.

Integrating JavaScript with Bootstrap Forms

Adding JavaScript to your form allows for dynamic behaviors and enhanced interactivity, which can significantly improve the user experience. Let’s explore two key aspects: implementing dynamic form behaviors like show/hide elements, and handling form submissions.

Dynamic Form Behaviors (Show/Hide Elements)

Using JavaScript, you can dynamically show or hide form elements based on user actions or inputs. This is useful in cases where you want to display additional fields based on certain selections.

Example: Dynamic Show/Hide with JavaScript:

Let’s create a form with a checkbox field that, when checked, shows an additional text input field. For this, add the code below to your HTML template.

<form>
  <div class="form-group">
    <input type="checkbox" id="toggleInput">
    <label for="toggleInput">Check to show more options</label>
  </div>
  <div class="form-group" id="additionalInput" style="display: none;">
    <label for="extraField">Extra Field:</label>
    <input type="text" class="form-control" id="extraField">
  </div>
</form>

Next, add the JavaScript code below to your JS file.

document.getElementById('toggleInput').addEventListener('change', function() {
  var additionalInput = document.getElementById('additionalInput');
  if (this.checked) {
    additionalInput.style.display = 'block';
  } else {
    additionalInput.style.display = 'none';
  }
});

In this example, the extra input field is initially hidden. When the checkbox is checked, the extra field is shown, and when unchecked, it is hidden again.

Form Submission Handling

Handling form submissions with JavaScript in a Bootstrap context allows you to intercept the submit event, validate the form data, and potentially submit the data asynchronously using AJAX.

Example: Form Submission with JavaScript:

Here’s how you can handle a form submission:

<form id="myForm">
  <div class="form-group">
    <label for="name">Name:</label>
    <input type="text" class="form-control" id="name">
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

JavaScript code to handle the form submission.

document.getElementById('myForm').addEventListener('submit', function(event) {
  event.preventDefault(); // Prevents the default form submission action
  
  // Form data processing
  var name = document.getElementById('name').value;
  console.log('Submitted Name:', name);

  // Optionally, submit the form data using AJAX here
});

In this example, the default form submission is prevented to allow for custom processing. You can then collect form data and, if required, use AJAX to submit the data to a server without reloading the page.

Check out the video below to learn more bout handling form submissions in HTML.

Best Practices for Bootstrap Forms

Accessibility Considerations

Accessibility in web forms ensures that all users, including those with disabilities, can use them effectively.

  1. Use of ARIA (Accessible Rich Internet Applications) Attributes: Incorporate ARIA roles and attributes to make forms more accessible. For instance, aria-label, aria-labelledby, and aria-describedby can provide context to screen readers.

  2. Labeling Form Elements: Always use <label> for each input field. For visually hidden labels (e.g., when using icon buttons), use class .sr-only to hide labels in a way that keeps them readable by screen readers.

  3. Ensuring Keyboard Navigation: Make sure that all form controls are accessible using the keyboard. This is crucial for users who rely on keyboard navigation.

  4. Error Identification: Identify and describe errors in form submission. Use alert roles like role=”alert” for error messages to ensure they are announced by screen readers.

Design Consistency

Maintaining a consistent design across all forms within a website or application is crucial for user experience.

  1. Consistent Layout and Styling: Use a consistent layout pattern (e.g., label alignment, button sizes) across all forms. Bootstrap’s grid system can help maintain layout consistency.

  2. Theming: Customize Bootstrap’s default theme to match your brand or site’s color scheme, typography, and other design elements.

  3. Responsive Design: Ensure forms are responsive and look good on all devices. Bootstrap’s responsive utilities should be utilized to achieve this.

  4. Feedback and States: Consistently use feedback indicators (like colors for success or error states) across all forms. Bootstrap’s form validation states and classes can be used for this.

Frequently Asked Questions

Below, we’ve answered the most common questions about creating forms with Bootstrap.

What is a Bootstrap Form?

A Bootstrap form is a web form created using Bootstrap classes, a popular front-end framework. Bootstrap forms are designed to be responsive and visually appealing. They utilize HTML, CSS, and optionally JavaScript, offering various styles and components like input fields, checkboxes, radio buttons, etc.

How Do I Make My Bootstrap Form Responsive?

Using Bootstrap’s built-in classes like form-control automatically adds responsiveness to your form elements. However, you can use Bootstrap’s predefined grid classes to customize the layout of your form. Doing so ensures that your form elements will adjust to different screen sizes.

How Does Form Validation Work in Bootstrap?

Bootstrap form validation is implemented using HTML5 and CSS. It provides visual feedback on the validation state of form elements. When a user submits a form, Bootstrap adds various CSS classes to invalid fields, such as is-invalid, displaying validation feedback messages. For custom validation logic, you might use JavaScript alongside Bootstrap’s styling.

How to get data from Bootstrap form?

To get data from a Bootstrap form, use standard HTML and JavaScript methods. Upon form submission, you can access the data from each form control either by using the FormData object or by accessing each element individually through its name or id. For example:

document.getElementById('myForm').addEventListener('submit', function(event) {
  event.preventDefault();
  var formData = new FormData(this);
  // Now, use formData.get('inputName') to access the data
});

How to use Bootstrap in react form?

To use Bootstrap in a React form, you can include Bootstrap’s CSS in your React project. This can be done by importing the Bootstrap CSS file into your main JavaScript file. For example:

import 'bootstrap/dist/css/bootstrap.min.css';

Then, use Bootstrap’s classes within your React components as usual. For more interactive elements, like modals or dropdowns, you might use libraries like react-bootstrap or reactstrap that reimplement Bootstrap components as React components.

Final Thoughts on Bootstrap Form

Most modern web applications include forms for collecting input from users. It has numerous use cases such as handling user registration, authentication, or user feedback forms.

In this tutorial, we’ve shown you how to use the Form components provided by Bootstrap. We also showed you a practical use case for these components by building a registration and login form.

At PureCode, we help you build User Interfaces faster than your competitors by providing ready-made components to build any aspect of your website.

Check out some of our templates.

Further Reading

If you enjoyed this content, here are other tutorials to help you become a better Bootstrap developer.

David Ozokoye

David Ozokoye

Software Engineer and Technical Writer