Mike Finocchiaro
Mike Finocchiaro

Reputation: 73

Dynamic Menu, Ajax, Ruby

Hey folks a nooby noob here,

My application has Dynamic Drop down menus for Category and Subcategory. When a category is selected the corresponding subcategory will change and display the category's subcategories - I have that set. But what I would like to accomplish is to hide the subcategory menu until a category is selected.

My Code i'm using for menus:

StaticPage Controller

          def update_subcategories
            # updates categories and subcategories based on product type selected
            category = Category.find(params[:category_id])
            # map to name and id for use in our options_for_select
            @subcategories = category.subcategories.map{|a| [a.name, a.id]}.insert(0, "Select a Product")
          end

View staticpage>home

    <div class="form-group">
      <%= f.label 'Choose a Product:' %>
      <%= f.collection_select :category_id,  @categories,  :id, :name, {:prompt   => "Select a Category"}, {:id => 'categories_select'} %>
    </div>
    <div class="form-group">
      <%= f.label 'Choose a brand:' %>
      <%= f.collection_select :subcategory_id, @subcategories, :id, :name, {:prompt   => "Select an Product"}, {:id => 'subcategories_select'} %>
    </div>


<script>
  $(document).ready(function() {
    var categories = '#categories_select';
    var subcategories = '#subcategories';


    $('#categories_select').change(function() {
      $.ajax({
        url: "<%= update_subcategories_path %>",
        data: {
          category_id : $('#categories_select').val()
        },
        dataType: "script"
      });
    });
  });
</script>

View staticpage>update_subcategories.js.erb

$('#subcategories_select').html("<%= escape_javascript(options_for_select(@subcategories)) %>");

Thanks in advance!


Update


USING @PAVAN SUGGESTION. HOWEVER DROPDOWN SUBCATEGORY MENU SEEMS TO BREAK: image of subcat. menu

Subcategory breaking

Upvotes: 1

Views: 152

Answers (1)

Pavan
Pavan

Reputation: 33542

Try the following

<script>
  $(document).ready(function() {
  $('#subcategories_select').hide();

    $('#categories_select').change(function() {
      $('#subcategories_select').show();
      $.ajax({
        url: "<%= update_subcategories_path %>",
        data: {
          category_id : $('#categories_select').val()
        },
        dataType: "script"
      });
    });
  });
</script>

You don't need these lines var categories = '#categories_select'; var subcategories = '#subcategories';

And also provide id subcategories_select to the sub_categories div instead to the sub_categories collection_select otherwise you will end showing the label Choose a brand: before changing the products collection_select.

<div class="form-group", id="subcategories_select">
  <%= f.label 'Choose a brand:' %>
  <%= f.collection_select :subcategory_id, @subcategories, :id, :name, {:prompt => "Select an Product"} %>
</div>

Upvotes: 2

Related Questions