richiepop2
richiepop2

Reputation: 348

dynamic drop down, show results

I have a model, Firms, with the following attributes: state and name. What I'd like to do is have the user view a list of names in a selected state. I was able to get the states in a dropdown box, but am struggling to have the names appear below after selecting a state. I looked throughout the options on here, but couldn't find a solution. I presume I need some javascript? Thanks for your help. Below is my view code.

 <h4>Select a State</h4>
<%= select_tag :state, options_for_select(Firm.order(:state).uniq.pluck(:state)) %>

Here is an example of what I'd like the results to look like:

User selects the state: Pennsylvania

Pennsylvania names appear below: Box Company Car Company . . .

Upvotes: 1

Views: 72

Answers (1)

mtkcs
mtkcs

Reputation: 1716

The user selects a state, a javascript event fires, an ajax call gets made and results gets showed under:

html

<%= select_tag :state, options_for_select(Firm.order(:state).uniq.pluck(:state)), id: "my-select" %>
<div id='names-wrapper'></div>

coffee

  $("#my-select").change ->
   state = $(this).val()
   alert(state)
   $.ajax
     url: "/firms/get_names"
     data:
       state: state
     success: (data) ->
       $('#names-wrapper').html('')
       $.each data, (index, value) -> 
         $('#names-wrapper').append(value)

routes

resources :firms do
  collection do
    get :get_names
  end
end

controller

class FirmsController < ApplicationControler
  def get_names
    state = params[:state]
    names = Firm.where(state: state).pluck(:name)
    return render json: names.to_json
  end
end

Upvotes: 1

Related Questions