Home > Net >  How to make radio buttons not clear after submitting Rails filter
How to make radio buttons not clear after submitting Rails filter

Time:05-06

I have a Rails app with a filter. The filter consists of two radio buttons. If the radio button "en" is selected, the english users are displayed and the same with "es" and spanish users.

This works fine. I can filter for english and spanish users. However, when the form is submitted, the selected radio button is cleared.

How do I make it that the selected radio button is still selected after submitting the form?

_filter.html.erb:

<%= form_with url: '/filter_users', method: :get do | form|%>
  <%= form.radio_button :language, 'en', onclick: "this.parentNode.submit();"%>
  <%= form.label :language_en, 'en' %>
  <%= form.radio_button :language, 'es', onclick: "this.parentNode.submit();" %>
  <%= form.label :language_es, 'es' %>
<% end %>

controller:

  def filter_users
    @users = User.all
    @users = @users.filter_by_language(params[:language]) if params[:language].present?
  end

model:

class User < ApplicationRecord
  scope :filter_by_language, ->(language) { where language: language }
end

I hope my question is clear. Thank you

CodePudding user response:

You can pass checked: true in the options hash to retain the value.

<%= form_with url: '/filter_users', method: :get do | form|%>
  <%= form.radio_button :language, 'en', checked: params[:language] == 'en', onclick: "this.parentNode.submit();"%>
  <%= form.label :language_en, 'en' %>
  <%= form.radio_button :language, 'es', checked: params[:language] == 'es', onclick: "this.parentNode.submit();" %>
  <%= form.label :language_es, 'es' %>
<% end %>

radio_button

  • Related