user3914956
user3914956

Reputation: 83

How to add class to form components with simple_form

Does anyone know how to add a class to a ruby on rails simple form, and how to add a class to an individual component so that I can style them later in CSS. Thank you

Upvotes: 1

Views: 5186

Answers (3)

antoniolulee
antoniolulee

Reputation: 1024

<%= f.button :submit, "Sign in", class: "submit-button" %>

Upvotes: 0

Michael Gaskill
Michael Gaskill

Reputation: 8042

Just adding a point to @bmac151's answer above.

For styling or dynamic scripting (e.g. javascript) purposes, you can also provide an ID to distinguish the elements from other elements of the same class by providing the id option, like so:

<%= simple_form_for @user, html: { id: 'simple-form' } do |f| %>
  <%= f.input :username, input_html: { class: 'special', id: 'username' } %>
  <%= f.input :password, input_html: { maxlength: 20, id: 'password' } %>
  <%= f.input :remember_me, input_html: { value: '1', id: 'remember_me' } %>
  <%= f.button :submit, id: 'submit-button' %>
<% end %>

This will give you unique IDs for all of the elements in the form, as well as the form itself.

From CSS, you can refer to these for styling, like this:

#simple-form {
    font-size: 125%;
}

#submit-button {
    text-transform: uppercase;
}

From Javascript, you can refer to elements by their element ID, as well. With this, you can apply dynamic behaviors to individual elements, rather than whole classes at a time. Here's a Javascript example:

var submit_button = document.getElementById("submit-button");

submit_button.addEventListener("click", function () {
    alert('Yeeehaaah!');
    submit_button.submit();
});

For fine-grained control, you'll want to use the id attribute rather than the class attribute; however, for theme-like control of elements, the class attribute is more useful.

Upvotes: 2

bmac151
bmac151

Reputation: 525

Straight from the simpleform docs:

It is also possible to pass any html attribute straight to the input, by using the :input_html option, for instance:

<%= simple_form_for @user do |f| %>
  <%= f.input :username, input_html: { class: 'special' } %>
  <%= f.input :password, input_html: { maxlength: 20 } %>
  <%= f.input :remember_me, input_html: { value: '1' } %>
  <%= f.button :submit %>
<% end %>

If you want to pass the same options to all inputs in the form (for example, a default class), you can use the :defaults option in simple_form_for. Specific options in input call will overwrite the defaults:

<%= simple_form_for @user, defaults: { input_html: { class: 'default_class' } } do |f| %>
  <%= f.input :username, input_html: { class: 'special' } %>
  <%= f.input :password, input_html: { maxlength: 20 } %>
  <%= f.input :remember_me, input_html: { value: '1' } %>
  <%= f.button :submit %>
<% end %>

Upvotes: 3

Related Questions