如何在Rails表单中保持同一行的复选框和标签?

And*_*raD 44 forms ruby-on-rails ruby-on-rails-3 twitter-bootstrap

如何将复选框的标签与包含表单的rails视图中的复选框保持在同一行?

目前标签在下一行:

<div class="span6 offset3">
<%= form_for(@user) do |f| %>
<%= render 'shared/error_messages', object: f.object %>

  <%= f.label :name %>
  <%= f.text_field :name %>

  <br>
  <%= f.check_box :terms_of_service %>
  <%= f.label :terms_of_service, "I agree to the #{link_to 'Terms of Service', policies_path}.".html_safe %>
  <br><br>

  <%= f.submit "Create my account", :class => "btn btn-large btn-primary" %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

谢谢你,亚历山德拉

Ben*_*gat 59

根据bootstrap wiki,它一定是

<label class="checkbox">
  <input type="checkbox"> Check me out
</label>
Run Code Online (Sandbox Code Playgroud)

在Ruby on Rails中是哪个

<%= f.label :terms_of_service do %>
  <%= f.check_box :terms_of_service %>
  I agree to the <%= link_to 'Terms of Service', policies_path %>.
<% end %>
Run Code Online (Sandbox Code Playgroud)


Dav*_*ood 22

看起来您正在使用Bootstrap,因此我建议您调整视图代码以使用Bootstrap文档的此部分中描述的水平表单布局:http://getbootstrap.com/css/#forms

  • 正如David Underwood所建议的那样,我最终使用了Bootstrap文档.一旦我将`:class =>"checkbox inline"添加到我的标签,标签就与复选框保持在同一行. (48认同)
  • 这个评论应该是一个单独的答案.它比接受的答案更好. (6认同)
  • 这里的每个答案都是错的.正确的代码是`<label class ="checkbox"> <input type ="checkbox">检查我</ label>` (3认同)
  • 如果有人使用simple_form来尝试完成此任务:`<%= f.input:terms_of_service,inline_label:"我同意......",标签:false%>`generate:`<label class ="checkbox"> <input type ="复选框"/>我同意...... </ label>` (3认同)

jai*_*444 5

 <br>
  <%= f.check_box :terms_of_service, :style => "float:left;" %>
  <%= f.label :terms_of_service, "I agree to the #{link_to 'Terms of Service', policies_path}.".html_safe, :style => "float:left;" %>
  <br>
Run Code Online (Sandbox Code Playgroud)


Pat*_*ick 5

对答案的评论是正确的,但它假设了一些关于元素顺序的细微差别.

正确答案如下:

<%= f.check_box :terms_of_service %>
<%= f.label :terms_of_service, "I agree to the #{link_to 'Terms of Service', policies_path}.".html_safe
                             , {class: "checkbox inline"} %>
Run Code Online (Sandbox Code Playgroud)

有两件事是必要的:

  1. 标签元素上的类
  2. checkbox元素必须位于label元素之前.

一旦你看到它工作,这是显而易见的,但form_for的所有其他样本总是在标签后面有输入,你需要更改为复选框.