robertwclark
robertwclark

Reputation: 47

Change content based on dropdown using Rails, Ajax and Jquery

I'm trying to display the recent scores of a team from a database based on the selection from a collection_select drop down. I know that I need to listen for the change event on the drop down but I don't know how to do the AJAX request or how to display the data in the view.

Upvotes: 0

Views: 2073

Answers (2)

hyperrjas
hyperrjas

Reputation: 10754

Ok, I will write a example with category and subcategory models.

The first is relation between models:

class Category
 has_many :subcategories
 has_many :objects
end

class Subcategory
 belongs_to :category
 has_many :objects
end

class Object
 belongs_to :category
 belongs_to :subcategory
end

Now the form on view, for example with simple_form gem (you can do it with form_for):

<%= simple_form_for(@object, :html => {:multipart => true }) do |f| %>
 <%= f.input :category, :collection => Category.all :prompt => "Select Category" %>
 <%= f.input :subcategory, :label_html => { :class => 'subcategory_label_class' } do %>
 <%= f.grouped_collection_select :subcategory_id, Category.order_by(:title), :subcategories, :title, :id, :name, include_blank: true %>
 <% end %>
 <%= f.button :submit %>
<% end %>

With this we grouped the subcategories with their parent category.

The next step you must add the code to your objects.js.coffee

$('#object_subcategory_id').parent().hide()
  subcategories = $('#object_subcategory_id').html()
  $('#object_category').change ->
    category = $('#object_category :selected').text()
    escaped_category = category.replace(/([ #;&,.+*~\':"!^$[\]()=>|\/@])/g, '\\$1')
    options = $(subcategories).filter("optgroup[label='#{escaped_category}']").html()
    if options
      $('#object_subcategory_id').html(options)
      $('.subcategory_label_class').show()
      $('#object_subcategory_id').parent().show()
    else
      $('#object_subcategory_id').empty()
      $('.subcategory_label_class').hide()
      $('#object_subcategory_id').parent().hide()

You can adapt this example to your needs.

I hope it helps.

Regards!

Upvotes: 2

user934801
user934801

Reputation: 1139

you need to build a separate controller and send the ajax request when your change event is triggered, the controller sends back a js response, that you have to handle in your clients javascript... the following link should give you an example http://blog.bernatfarrero.com/jquery-and-rails-3-mini-tutorial/

Upvotes: 2

Related Questions