1

I have a radio button built using Ruby as in below

      <p>Which design do you prefer to use? </p>
      <% [ 'Design 1', 'Design 2', 'Design 3', 'Design 4', 'Design 5' ].each do |theme| %>
          <br><%= radio_button_tag 'theme', theme, @theme == theme %>
          <%= label_tag "theme_#{theme}", theme.humanize %>
      <% end %>

I want to ensure that the first element (aka Design 1) is always checked by default unless user choses some other design.

0

1 Answer 1

4

You can do this: Pass in checked to check the item

<%= radio_button_tag 'theme', theme, checked: @theme.FIELD_NAME == 'design' %>

See here for details http://apidock.com/rails/ActionView/Helpers/FormTagHelper/radio_button_tag

Answering your comment:

Ahmm I dont understand? :( So <%= radio_button_tag 'theme', theme %> becomes <%= radio_button_tag 'theme', theme, checked: @theme.FIELD_NAME == 'design' %> ?? But this throws an error? I just want the first radio button element to be selected by default –

FIELD_NAME is the name of the column on your Model. To just check the first item you can try this: Just add the checked: true keyword

<%= radio_button_tag 'theme', theme, @theme == theme, checked: true %>

Ok so you need to do the following:

<% [ 'Design 1', 'Design 2', 'Design 3', 'Design 4', 'Design 5' ].each_with_index do |theme, i| %>
  <% if i == 0 %>
      <br><%= radio_button_tag 'theme', theme, @theme == theme, checked: true %>
  <% else %>
      <br><%= radio_button_tag 'theme', theme, @theme == theme %>
  <% end %>
  <%= label_tag "theme_#{theme}", theme.humanize %>
<% end %>
Sign up to request clarification or add additional context in comments.

5 Comments

Ahmm I dont understand? :( So ` <%= radio_button_tag 'theme', theme %> ` becomes <%= radio_button_tag 'theme', theme, checked: @theme.FIELD_NAME == 'design' %> ?? But this throws an error? I just want the first radio button element to be selected by default
Here in your case, use this: <%= radio_button_tag 'theme', theme, @theme == theme, checked: true %> Remember to upvote and check answers.
Hi, Thanks. All the elements stays checked=checked in the source code and the last element checked . I do not want all element to have checked=checked. :(
@theme == theme, checked: true should just be true
In fact, the code can be simplified to just <% [ 'Design 1', 'Design 2', 'Design 3', 'Design 4', 'Design 5' ].each_with_index do |theme, i| %> <br><%= radio_button_tag 'theme', theme, @theme == theme || i == 0 %> <%= label_tag "theme_#{theme}", theme.humanize %> <% end %>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.