1
votes

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 %>
2
question is where do you put the phone-name relation?kasperite
question is how to auto fill the name that correspond to the selected phone numberAlaa Othman

2 Answers

1
votes

Not sure how you build the relationship between name and phone number but you can auto fill name inside autocomplete select event like this

$(document).ready ->
  $('#patient_phone').autocomplete
    source: "/patients/index"
    select: (event, ui) ->
      selected_phone_number = $(event.target).val()
      // Fill in value for name field here

See: http://api.jqueryui.com/autocomplete/#event-select

1
votes

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 patient_nameto the form field.