I have a Rails 3.2.20 app which I have a form setup that selects a facility which has a facility_name
and facility_address
field in the facility model. This is a relationship between the Call
and Facility
model to allow facilities to be assigned to calls.
Currently I'm able to select a facility and assign it no problem by selecting the name from a dropdown/search using select2
. But what I want to be able to do is when selecting the facility have a small div display next to it with the facility_address
for the specific facility.id
. So when I select 24 hour emergency room, a small div will show the address for the facility.
I'm unsure as to how to do this with jQuery or CoffeeScript as I'm a bit rusty. Attached is a screenshot of what my form looks like. Below is what I have so far to handle the jQuery, but I need to figure out a way to pass a data attribute to grouped_collection_select
so I can get the address
data field to display with jQuery. Whenever I select a facility the div will pop out with "undefined"
I'm not sure if I can even pass a data attribute like data: {address: :facility_address}
. Trying this yields errors. There's go to be some way to do this. Or perhaps restructuring it to a select
form helper and use group_options_for_select
I'm doing searches on how to display data from a form field using jQuery or CoffeeScript but so far I haven't found anything specific.
If you need code examples of my form or more data about my models relationships, please let me know. But basically I just need to display a facility address once the facility.id is selected in the form.
_form.html.erb
<%= f.grouped_collection_select :transfer_from_id, Region.order(:area), :active_facilities, :area, :id, :facility_name, {include_blank: true}, class: 'select' %><div id ="transfer-from-address"></div>
region.rb
class Region < ActiveRecord::Base
attr_accessible :area
has_many :calls
has_many :facilities
def active_facilities
self.facilities.active
end
end
calls.js.coffee
jQuery ->
facilities = $('#call_transfer_from_id').html()
update_facilities = ->
region = $('#call_region_id :selected').text()
options = $(facilities).filter("optgroup[label=#{region}]").html()
if options
# Set the options and include a blank option at the top
$('#call_transfer_from_id').html("<option value=''></option>" + options)
# Ensure that the blank option is selected
$('#call_transfer_from_id').attr("selected", "selected")
else
$('#call_transfer_from_id').empty()
$('#call_region_id').change ->
update_facilities()
update_facilities()
jQuery ->
$("#call_transfer_from_id").on "change", (e) ->
selected = $("#call_transfer_from_id option:selected")
$("#transfer-from-address").html("""
<h3>#{selected.data("address")}</h3>
""")