Alaa Othman Alaa Othman - 1 year ago 96
jQuery Question

Dynamic forms - Auto fill fields based on previous auto complete

I have a form with two fields

what i want is when the user selects a phone number using ajax autocomplete the name field will be auto filled with the name that correspond to that phone number.

Watching that Railscasts episode i was able to make ajax autocomplete works, any clean way of doing the auto filling?


class PatientsController < ApplicationController
def index
@patients = Patient.order(:phone).where('phone like ?', "%#{params[:term]}%")
json_data =
render json: json_data

$(document).ready ->
source: "/patients/index"


<%= f.fields_for :patient, appointment.patient do |patient| %>
<%= patient.text_field :phone, id: 'patient_phone' %>
<%= patient.text_field :name %>
<%= f.submit %>
<% end %>

Answer Source

The solution was to modify both

the index action

def index
  @patients = Patient.order(:phone).where(
              'phone like ?', "%#{params[:term]}%")
  render :json => @patients.collect { 
                  |x| {:label =>, 
                       :value =>, 
                       :name =>} 

the ajax request

$(document).ready ->
  source: "/patients/index", messages: noResults: '', 
          results: func = -> ''
  select: (event, ui) -> $("#patient_name").val(
  focus: (event, ui) -> $(".ui-helper-hidden-accessible").hide();

And add the id to patient_name to the form field.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download