Переход на v4

Bootstrap Checkboxes

Checkboxes are used if you want the user to select any number of options from a list of preset options.

The following example contains three checkboxes. The last option is disabled:


Example

<div class=»form-check»>  <label class=»form-check-label»>    <input type=»checkbox» class=»form-check-input» value=»»>Option 1  </label></div><div class=»form-check»>  <label class=»form-check-label»>    <input type=»checkbox» class=»form-check-input» value=»»>Option 2  </label></div> <div class=»form-check»>  <label class=»form-check-label»>    <input type=»checkbox» class=»form-check-input» value=»» disabled>Option 3  </label></div>

Example explained

Use a wrapper element with to ensure proper margins for labels and checkboxes.

Add the class to label elements, and to style checkboxes properly inside the container.

Custom Checkbox

To create a custom checkbox, wrap a container element, like <div>, with a class of and around the checkbox. Then add the to the input with type=»checkbox».

Tip: If you use labels for accompanying text, add the class to it. Note that the value of the for attribute should match the id of the checkbox:

Custom checkbox

Default checkbox

Example

<form>  <div class=»custom-control custom-checkbox»>    <input type=»checkbox» class=»custom-control-input» id=»customCheck» name=»example1″>    <label class=»custom-control-label» for=»customCheck»>Check this custom checkbox</label>  </div></form>

Custom File Upload

To create a custom file upload, wrap a container element with a class of around the input with type=»file». Then add the to it.

Tip: If you use labels for accompanying text, add the class to it. Note that the value of the for attribute should match the id of the checkbox:

Choose file

Note that you also have to include some jQuery code if you want the name of the file to appear when you select a specific file:

Example

<form>  <div class=»custom-file»>    <input type=»file» class=»custom-file-input» id=»customFile»>    <label class=»custom-file-label» for=»customFile»>Choose file</label>  </div></form><script>// Add the following code if you want the name of the file appear on select $(«.custom-file-input»).on(«change», function() {  var fileName = $(this).val().split(«\\»).pop();  $(this).siblings(«.custom-file-label»).addClass(«selected»).html(fileName); });</script>

Forms

Various form elements have been rebooted for simpler base styles. Here are some of the most notable changes:

  • s have no borders, padding, or margin so they can be easily used as wrappers for individual inputs or groups of inputs.
  • s, like fieldsets, have also been restyled to be displayed as a heading of sorts.
  • s are set to to allow to be applied.
  • s, s, s, and s are mostly addressed by Normalize, but Reboot removes their and sets , too.
  • s are modified to only be resizable vertically as horizontal resizing often “breaks” page layout.
  • s and button elements have when .

These changes, and more, are demonstrated below.

Pointers on buttons

Reboot includes an enhancement for to change the default cursor to . Add this attribute to elements to help indicate elements are interactive. This role isn’t necessary for elements, which get their own change.

Non-button element button

Static Controls

You can create a static control like this:

<%= f.static_control :email %>

Here’s the output for a horizontal layout:

<div class="form-group">
  <label class="col-sm-2 form-control-label" for="user_email">Email</label>
  <div class="col-sm-10">
    <input class="form-control-plaintext" id="user_email" name="user" readonly="readonly" type="text" value="test@email.com"/>
  </div>
</div>

You can also create a static control that isn’t based on a model attribute:

<%= f.static_control :field_name, label: "Custom Static Control", value: "Content Here" %>

may be any name that isn’t already used in the form. Note that you may get «unpermitted parameter» messages in your log file with this approach.

You can also create the static control the following way, if you don’t need to get the value of the static control as a parameter when the form is submitted:

<%= f.static_control label: "Custom Static Control", value: "Content Here", name: nil %>

(If you neither provide a field name nor , the Rails code that submits the form will give a JavaScript error.)

Prior to version 4 of , you could pass a block to the method. The value of the block would be used for the content of the static «control». Bootstrap 4 actually creates and styles a disabled input field for static controls, so the value of the control has to be specified by the option. Passing a block to no longer has any effect.

Форма в одну строку

Используйте класс .form-inline, чтобы элементы формы отображались как строчно-блочные и выравнивались по левому краю. Используйте вспомогательные класса (например, mr-sm-2), чтобы добавить пространство между элементами.

Обратите внимание, всё это применимо только тогда, когда область просмотра имеет ширину не меньше 576 пикселей. Имя Фамилия Отправить

<link rel=»stylesheet» href=»https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css»> <form class=»form-inline»> <label class=»mr-sm-2 mb-0″ for=»first_name»>Имя</label> <input type=»text» class=»form-control mr-sm-2 mb-2 mb-sm-0″ id=»first_name» name=»first_name»> <label class=»mr-sm-2 mb-0″ for=»last_name»>Фамилия</label> <input type=»text» class=»form-control mr-sm-2 mb-2 mb-sm-0″ id=»last_name» name=»last_name»> <button type=»submit» class=»btn btn-primary mt-2 mt-sm-0″>Отправить</button> </form>

Validation and Errors

Rails normally wraps fields with validation errors in a , but this behaviour isn’t consistent with Bootstrap 4 styling. By default, generations in-line errors which appear below the field. But it can also generate errors on the label, or not display any errors, leaving it up to you.

Inline Errors

By default, fields that have validation errors will be outlined in red and the error will be displayed below the field. Here’s an example:

<div class="form-group">
  <label class="form-control-label" for="user_email">Email</label>
  <input class="form-control is-invalid" id="user_email" name="user" type="email" value="">
  <small class="invalid-feedback">can't be blank</small>
</div>

You can turn off inline errors for the entire form like this:

<%= bootstrap_form_for(@user, inline_errors: false) do |f| %>
  ...
<% end %>

Label Errors

You can also display validation errors in the field’s label; just turn on the option. Here’s an example:

<%= bootstrap_form_for(@user, label_errors: true) do |f| %>
  ...
<% end %>

By default, turning on will also turn off . If you want both turned on, you can do that too:

<%= bootstrap_form_for(@user, label_errors: true, inline_errors: true) do |f| %>
  ...
<% end %>

Alert Messages

To display an error message with an error summary, you can use the helper. This won’t output anything unless a model validation has failed.

<%= f.alert_message "Please fix the errors below." %>

Which outputs:

<div class="alert alert-danger">
  <p>Please fix the errors below.</p>
  <ul class="rails-bootstrap-forms-error-summary">
    <li>Email can't be blank</li>
  </ul>
</div>

You can turn off the error summary like this:

<%= f.alert_message "Please fix the errors below.", error_summary: false %>

To output a simple unordered list of errors, use the helper.

<%= f.error_summary %>

Which outputs:

<ul class="rails-bootstrap-forms-error-summary">
  <li>Email can't be blank</li>
</ul>

Errors On

If you want to display a custom inline error for a specific attribute not represented by a form field, use the helper.

<%= f.errors_on :tasks %>

Which outputs:

<div class="alert alert-danger">Tasks can't be blank.</div>

You can hide the attribute name like this:

<%= f.errors_on :tasks, hide_attribute_name: true %>

Which outputs:

<div class="alert alert-danger">can't be blank.</div>

Form Validation

You can use different validation classes to provide valuable feedback to users. Add either or to the element, depending on whether you want to provide validation feedback before or after submitting the form. The input fields will have a green (valid) or red (invalid) border to indicate what’s missing in the form. You can also add a or message to tell the user explicitly what’s missing, or needs to be done before submitting the form.

Example

In this example, we use to indicate what’s missing before submitting the form:

<form action=»/action_page.php» class=»was-validated»>  <div class=»form-group»>    <label for=»uname»>Username:</label>    <input type=»text» class=»form-control» id=»uname» placeholder=»Enter username» name=»uname» required>    <div class=»valid-feedback»>Valid.</div>    <div class=»invalid-feedback»>Please fill out this field.</div>  </div>  <div class=»form-group»>    <label for=»pwd»>Password:</label>    <input type=»password» class=»form-control» id=»pwd» placeholder=»Enter password» name=»pswd» required>    <div class=»valid-feedback»>Valid.</div>    <div class=»invalid-feedback»>Please fill out this field.</div>  </div>  <div class=»form-group form-check»>    <label class=»form-check-label»>      <input class=»form-check-input» type=»checkbox» name=»remember» required> I agree on blabla.      <div class=»valid-feedback»>Valid.</div>      <div class=»invalid-feedback»>Check this checkbox to continue.</div>    </label>  </div>  <button type=»submit» class=»btn btn-primary»>Submit</button></form>

Example

In this example, we use , which will add the validation effect AFTER the form has been submitting (if there’s anything missing). Note that you will also have to add some jQuery code for this example to work properly:

<form action=»/action_page.php» class=»needs-validation» novalidate>  <div class=»form-group»>    <label for=»uname»>Username:</label>    <input type=»text» class=»form-control» id=»uname» placeholder=»Enter username» name=»uname» required>    <div class=»valid-feedback»>Valid.</div>    <div class=»invalid-feedback»>Please fill out this field.</div>  </div>  <div class=»form-group»>    <label for=»pwd»>Password:</label>    <input type=»password» class=»form-control» id=»pwd» placeholder=»Enter password» name=»pswd» required>    <div class=»valid-feedback»>Valid.</div>    <div class=»invalid-feedback»>Please fill out this field.</div>  </div>  <div class=»form-group form-check»>    <label class=»form-check-label»>      <input class=»form-check-input» type=»checkbox» name=»remember» required> I agree on blabla.      <div class=»valid-feedback»>Valid.</div>      <div class=»invalid-feedback»>Check this checkbox to continue.</div>    </label>  </div>  <button type=»submit» class=»btn btn-primary»>Submit</button></form><script>// Disable form submissions if there are invalid fields(function() {  ‘use strict’;  window.addEventListener(‘load’, function() {    // Get the forms we want to add validation styles to    var forms = document.getElementsByClassName(‘needs-validation’);    // Loop over them and prevent submission    var validation = Array.prototype.filter.call(forms, function(form) {      form.addEventListener(‘submit’, function(event) {        if (form.checkValidity() === false) {          event.preventDefault();          event.stopPropagation();        }        form.classList.add(‘was-validated’);      }, false);    });  }, false);})();</script>

Usage

bootstrap_form_for

To get started, use the helper in place of the Rails helper. Here’s an example:

<%= bootstrap_form_for(@user) do |f| %>
  <%= f.email_field :email %>
  <%= f.password_field :password %>
  <%= f.check_box :remember_me %>
  <%= f.submit "Log In" %>
<% end %>

This generates the following HTML:

<form accept-charset="UTF-8" action="/users" class="new_user" id="new_user" method="post">
  <div class="form-group">
    <label for="user_email">Email</label>
    <input class="form-control" id="user_email" name="user" type="email">
  </div>
  <div class="form-group">
    <label for="user_password">Password</label>
    <input class="form-control" id="user_password" name="user" type="password">
  </div>
  <div class="form-check">
    <input name="user" type="hidden" value="">
    <input class="form-check-input" id="user_remember_me" name="user" type="checkbox" value="1">
    <label class="form-check-label" for="user_remember_me">Remember me</label>
  </div>
  <input class="btn btn-secondary" name="commit" type="submit" value="Log In">
</form>

bootstrap_form_tag


If your form is not backed by a model, use the . Usage of this helper is the same as , except no model object is passed in as the first argument. Here’s an example:

<%= bootstrap_form_tag url: '/subscribe' do |f| %>
  <%= f.email_field :email, value: 'name@example.com' %>
  <%= f.submit %>
<% end %>

bootstrap_form_with

Note that in Rails 5.1 does not add IDs to form elements and labels by default, which are both important to Bootstrap markup. This behaviour is corrected in Rails 5.2.

To get started, just use the helper in place of . Here’s an example:

<%= bootstrap_form_with(model: @user, local: true) do |f| %>
  <%= f.email_field :email %>
  <%= f.password_field :password %>
  <%= f.check_box :remember_me %>
  <%= f.submit "Log In" %>
<% end %>

This generates:

<form role="form" action="/users" accept-charset="UTF-8" method="post">
  <input name="utf8" type="hidden" value="&#x2713;" />
  <div class="form-group">
    <label class="required" for="user_email">Email</label>
    <input class="form-control" type="email" value="steve@example.com" name="user" />
  </div>
  <div class="form-group">
    <label for="user_password">Password</label>
    <input class="form-control" type="password" name="user" />
    <small class="form-text text-muted">A good password should be at least six characters long</small>
  </div>
  <div class="form-check">
    <input name="user" type="hidden" value="">
    <input class="form-check-input" id="user_remember_me" name="user" type="checkbox" value="1">
    <label class="form-check-label" for="user_remember_me">Remember me</label>
  </div>
  <input type="submit" name="commit" value="Log In" class="btn btn-secondary" data-disable-with="Log In" />
</form>

supports both the and use cases in .

Other Tips and Edge Cases

By their very nature, forms are extremely diverse. It would be extremely difficult to provide a gem that could handle every need. Here are some tips for handling edge cases.

Empty But Visible Labels

Some third party plug-ins require an empty but visible label on an input control. The option generates a label that won’t appear on the screen, but it’s considered invisible and therefore doesn’t work with such a plug-in. An empty label (e.g. ) causes the underlying Rails helper to generate a label based on the field’s attribute’s name.

The solution is to use a zero-width character for the label, or some other «empty» HTML. For example:

label: "&#8203;".html_safe

or

label: "<span></span>".html_safe

Inline Custom Form Controls

If you want the custom form controls to sit side by side (inline), add the to the wrapper/container:

Custom radio

Custom radio

Example

<form>  <div class=»custom-control custom-radio custom-control-inline»>    <input type=»radio» class=»custom-control-input» id=»customRadio» name=»example» value=»customEx»>    <label class=»custom-control-label» for=»customRadio»>Custom radio 1</label>  </div>  <div class=»custom-control custom-radio custom-control-inline»>    <input type=»radio» class=»custom-control-input» id=»customRadio2″ name=»example» value=»customEx»>    <label class=»custom-control-label» for=»customRadio2″>Custom radio 2</label>  </div> </form>

Usage

Bootstrap Icons are SVGs, so you can include them into your HTML in a few ways depending on how your project is setup. Bootstrap Icons include a and of by default to allow for easy resizing via .

Sprite

Use the SVG sprite to insert any icon through the element. Use the icon’s filename as the fragment identifier (e.g., is ). SVG sprites allow you to reference an external file similar to an element, but with the power of for easy theming.

Copy the Bootstrap icons SVGs to your directory of choice and reference them like normal images with the element.

CSS

You can also use the SVG within your CSS (be sure to escape any characters, such as to when specifying hex color values). When no dimensions are specified via and on the , the icon will fill the available space.

The attribute is required if you wish to resize icons with . Note that the attribute is required.

Working with SVGs

SVGs are awesome to work with, but they do have some known quirks to work around. Given the numerous ways in which SVGs can be used, we haven’t included these attributes and workarounds in our code.

  • Focus handling is broken in Internet Explorer and Edge. When embedding your SVGs, add to the element. Learn more on Stack Overflow.

  • Browsers inconsistently announce SVGs as tags with voice assistance. Include when possible to avoid any issues.

  • Safari skips when used non-focusable SVGs. As such, use when embedding the file and use CSS to visually hide an equivalent label.

Community


Stay up to date on the development of Bootstrap and reach out to the community with these helpful resources.

  • Follow @getbootstrap on Twitter.
  • Read and subscribe to The Official Bootstrap Blog.
  • Join the official Slack room.
  • Chat with fellow Bootstrappers in IRC. On the server, in the channel.
  • Implementation help may be found at Stack Overflow (tagged ).
  • Developers should use the keyword on packages which modify or add to the functionality of Bootstrap when distributing through npm or similar delivery mechanisms for maximum discoverability.

You can also follow @getbootstrap on Twitter for the latest gossip and awesome music videos.

Submit Buttons

The CSS classes are automatically added to your submit buttons.

<%= f.submit %>

You can also use the helper, which adds to your submit button:

<%= f.primary "Optional Label" %>

You can specify your own classes like this:

<%= f.submit "Log In", class: "btn btn-success" %>

If the helper receives a option or a block, it will be rendered as an HTML button, instead of an input tag. This allows you to specify HTML content and styling for your buttons (such as adding illustrative icons to them). For example, the following statements

<%= f.primary "Save changes <span class='fa fa-save'></span>".html_safe, render_as_button: true %>

<%= f.primary do
      concat 'Save changes '
      concat content_tag(:span, nil, class: 'fa fa-save')
    end %>

are equivalent, and each of them both be rendered as:

<button name="button" type="submit" class="btn btn-primary">Save changes <span class="fa fa-save"></span></button>

If you wish to add additional CSS classes to your button, while keeping the default ones, you can use the option. This is particularly useful for adding extra details to buttons (without forcing you to repeat the Bootstrap classes), or for element targeting via CSS classes. Be aware, however, that using the option will discard any extra classes you add. As an example, the following button declarations

<%= f.primary "My Nice Button", extra_class: 'my-button' %>

<%= f.primary "My Button", class: 'my-button' %>

will be rendered as

<input type="submit" value="My Nice Button" class="btn btn-primary my-button" />

<input type="submit" value="My Button" class="my-button" />

(some unimportant HTML attributes have been removed for simplicity)

Disabled state

Make buttons look inactive by adding the boolean attribute to any element.

Primary button Button

Disabled buttons using the element behave a bit different:

  • s don’t support the attribute, so you must add the class to make it visually appear disabled.
  • Some future-friendly styles are included to disable all on anchor buttons. In browsers which support that property, you won’t see the disabled cursor at all.
  • Disabled buttons should include the attribute to indicate the state of the element to assistive technologies.

Link functionality caveat

The class uses to try to disable the link functionality of s, but that CSS property is not yet standardized. In addition, even in browsers that do support , keyboard navigation remains unaffected, meaning that sighted keyboard users and users of assistive technologies will still be able to activate these links. So to be safe, add a attribute on these links (to prevent them from receiving keyboard focus) and use custom JavaScript to disable their functionality.

Inputs

Bootstrap inputs

Bootstrap input is a special field which is used in order to receive data from the user. Used mostly in a variety of web-based forms.

You can use default bootstrap style or the Material Design version.

In case you want to create your custom form, have a look at specific pages of our documentation from the list below or use our Form Builder:

Drag & drop form builder

  • Predefined forms (Login, Register, Subscription, Contact)
  • Autocomplete
  • Checkbox
  • Contact form — how to send an email
  • File input
  • Form within modal
  • Input
  • Multiselect
  • Radio button
  • Search
  • Select
  • Slider
  • Additional styles & customization
  • Switch
  • Textarea
  • Validation

Горизонтальная форма

Вы можете использовать классы сетки Bootstrap для создания горизонтальных форм. Просто укажите, сколько колонок должен занимать каждый элемент. В частности, добавьте класс .row к .form-group и класс .col-*-* или .col-* для каждой колонки.

Вы также должны добавить класс .col-form-label к элементу <label>, чтобы метка относительно текстовых полей расположилась по центру вертикали.

<link rel=»stylesheet» href=»https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css»> <div class=»container»> <form> <div class=»form-group row»> <label for=»first_name» class=»col-xs-3 col-form-label mr-2″>Имя</label> <div class=»col-xs-9″> <input type=»text» class=»form-control» id=»first_name» name=»first_name»> </div> </div> <div class=»form-group row»> <label for=»last_name» class=»col-xs-3 col-form-label mr-2″>Фамилия</label> <div class=»col-xs-9″> <input type=»text» class=»form-control» id=»last_name» name=»last_name»> </div> </div> <div class=»form-group row»> <div class=»offset-xs-3 col-xs-9″> <button type=»submit» class=»btn btn-primary»>Отправить</button> </div> </div> </form> </div>

Bootstrap 4 против Bootstrap 3

Когда речь идёт о горизонтальных формах, имеются некоторые незначительные различия между Bootstrap 4 и Bootstrap 3.

Сетки При использовании сеток для макета формы, Bootstrap 4 требует класс .row. Этот класс не является обязательным для форм Bootstrap 3 (хотя по прежнему обязателен для сеток Bootstrap 3). Метки Bootstrap 4 использует .col-form-label в сетке макета формы, тогда как Bootstrap 3 использует .control-label

Обратите внимание, что Bootstrap 4 изначально использовал .form-control-label, но впоследствии заменил его на .col-form-label. Класс .form-horizontal Bootstrap 3 требует класс .form-horizontal, тогда как Bootstrap 4 нет.

Создание форм в Bootstrap

Платформа Bootstrap 3 содержит глобальные стили и классы, которые предназначены для оформления HTML форм и индивидуальных элементов управления.

Глобальные стили представляют собой определённые CSS правила, которые определяют внешний вид элементов управления на веб-странице. Эти стили элементы управления получают автоматически, и веб-разработчику их явно задавать не требуется.

В Twitter Bootstrap 3 основная задача для веб-разработчика в основном сводится в добавлении необходимых классов для элементов управления, форм и контейнеров.

Основные моменты при создании и оформлении формы представим в виде следующих этапов:

  • Указать вид формы. В Bootstrap 3 различают следующие виды форм: вертикальная (без добавления класса), горизонтальная () и в одну строку ().
  • Добавить к необходимым текстовым элементам управления , , класс , чтобы установить им ширину, равную 100% (всю доступную ширину родительского элемента).
  • Поместить каждую надпись () и элемент управления в контейнер … с классом . Это необходимо сделать, чтобы задать для элементов в форме оптимальные отступы.

Rich Text Areas AKA Trix Editor

If you’re using Rails 6, supports the helper.

<%= f.rich_text_area(:life_story) %>

will be rendered as:

<div class="form-group">
  <label for="user_life_story">Life story</label>
  <input type="hidden" name="user" id="user_life_story_trix_input_user"/>
  <trix-editor id="user_life_story" data-blob-url-template="http://test.host/rails/active_storage/blobs/:signed_id/:filename" data-direct-upload-url="http://test.host/rails/active_storage/direct_uploads" input="user_life_story_trix_input_user" class="trix-content form-control"/>
  </trix-editor>
</div>

Responsive tables

Create responsive tables by adding to any to make them scroll horizontally on small devices (under 768px). When viewing on anything larger than 768px wide, you will not see any difference in these tables.

Vertical clipping/truncation

Responsive tables make use of , which clips off any content that goes beyond the bottom or top edges of the table. In particular, this can clip off dropdown menus and other third-party widgets.

# Table heading Table heading Table heading Table heading Table heading Table heading
1 Table cell Table cell Table cell Table cell Table cell Table cell
2 Table cell Table cell Table cell Table cell Table cell Table cell
3 Table cell Table cell Table cell Table cell Table cell Table cell
# Table heading Table heading Table heading Table heading Table heading Table heading
1 Table cell Table cell Table cell Table cell Table cell Table cell
2 Table cell Table cell Table cell Table cell Table cell Table cell
3 Table cell Table cell Table cell Table cell Table cell Table cell

С этим читают