Dynamic Category and Subcategory Selector [Rails 6]

Viewed 486

I want to create a Category Select tag that when you select the category, changes the select options for another select_tag with the subcategories that belongs to the category selected.

I tried stimulus reflex, but i'm not happy with the result, other ways to do it? It's for the _form.html.erb for the Project model, how do i do it without refreshing the page?

Selects

1 Answers

Pass your categories including their subcategories with it

@categories = Category.includes(:subcategories)

Then iterate over it on the first selector.

<select id="category" name="category_id">
  <% @categories.each do |category| %>
    <option value="<%= category.id %>"><%= category.name %></option>
  <% end %>
</select>

<select id="subcategory" name="subcategory_id" disabled></select>

Use javascript on the second selector to generate his elements dynamically based on first input value. Place a listener on the first, to track when it's value changes.

<script>
  var categories = <%= @categories %>
  $("#category").change(function(e) {
    var subcategories = [];
    var selectedCategoryId = $(this).val();

    $('#subcategory').empty();

    subcategories = categories.find(x => x.id === selectedCategoryId).subcategories;
    subcategories.each(function (sub) {
       $('#subcategory').appendChild(`<option value="${sub.id}">${sub.name}</option>`);
    });
    $('#subcategory').prop('disabled', false);
  });
</script>

This would work. You could also create a helper and call it by an ajax as well.

Related