Add custom class to form fields

2019-08-27 02:41发布

问题:

Having such form

<%= form_tag 'search', method: 'get', class: 'form-horizontal' do %>
     <%= label_tag  :search, 'Enter url here' %>
     <%= text_field_tag :search  %>
     <%= submit_tag 'Get it!' %>
    <% end %>

Code above adds class='form-horizontal' for form tag.

How can I add class='form-control' for each input field ?

回答1:

Try this:

text_field_tag :search, nil, class: 'form-control'

For future reference:

text_field_tag(name, value = nil, options = {})

text_field_tag :search
# => <input id="search" name="search" type="text" />

text_field_tag :search, 'Enter your search query here'
# => <input id="search" name="search" type="text" value="Enter your search query here" />

text_field_tag :search, nil, class: 'form-control'
# => <input class="form-control" id="search" name="search" type="text" />


回答2:

<%= form_tag 'search', method: 'get', class: 'form-horizontal' do %>
   <%= label_tag  :search, 'Enter url here' %>
   <%= text_field_tag :search, {:class => 'form-control'}  %>
   <%= submit_tag 'Get it!' %>
<% end %>