Colin Wu
Colin Wu

Reputation: 699

Auto-update text field depending on selected option

Rails ver: 4.0.0

Hi all,

In my form I have a drop-down selection of client names. I would like to have a text box containing the client's address be updated whenever the selection is changed (before clicking the submit button to finalize the update). The reason is I am working with legacy data from another project where there can be several client entries with the same name but different addresses (e.g. large corp with several offices).

Obviously (perhaps?) I can't use any of the client-side script solutions since the new address has to be retrieved from the model - unless there is a way for java/coffee script to do a db lookup that I don't know about (which is highly likely since I only have a superficial acquaintance with them).

Thanks for any hints or pointers.

Upvotes: 2

Views: 1127

Answers (1)

NM Pennypacker
NM Pennypacker

Reputation: 6942

You can do something like this assuming you have @client:

Add a hidden div to your view to hold a data attribute:

<div id="client_id" style="display:none;" data-client="<%= @client.id %>"></div>

In somefile.js.coffee:

App ||= {}

App.client =
address = $("#id_of_your_select_field")
client = $("#client_id).data('client')

toggler.on 'change', ( e ) ->
  App.client.getAddress


getAddress: ->
  $ajax(
    type: 'post'
    url: "/get_address"
    client_id: client
    success: ( data, status, xhr ) ->
    # you could parse JSON here if you want, or keep reading and leave this blank
  )

in routes.rb

post '/get_address/:client_id', to: 'clients#return_address'

in clients_controller.rb

def return_address
  @client = Client.find(params[:client_id])
  respond_to do |format|
    format.js
  end
end

and in views/clients/return_address.js do:

var clientAddress = $("#the_civ_with_the_address");
clientAddress.html( "<%= j render( :partial => 'clients/address', :locals => { :client => @client } ) %>" );

Then make a partial with the client info at app/views/clients/_address.html.erb

Upvotes: 1

Related Questions