Alaa Othman Alaa Othman - 3 months ago 13
jQuery Question

Dynamic forms - Auto fill fields based on previous auto complete

I have a form with two fields

phone
and
name
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?

patients_controller

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


reservations.coffee

$(document).ready ->
$('#patient_phone').autocomplete
source: "/patients/index"


_form.erb

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

Answer

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 => x.phone, 
                       :value => x.phone, 
                       :name => x.name} 
                      }.compact
end

the ajax request

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

And add the id to patient_name to the form field.

Comments