I have a form with a text field that uses jQuery-UI autocomplete widget.
I’m loading this form as a partial using AJAX with Ruby on Rails <li id="activity_<%= activity.id %>"><%= link_to activity.address, edit_activity_path(activity), :remote => true %></li>
Since the form is being loaded after document.ready, the autocomplete jQuery widget is not binding to the DOM element.
Since this isn’t a jQuery AJAX call, I don’t think that there is a success callback that I can use to bind the autocomplete widget with after the Ajax call.
I’m not sure how to use the .on() function that I’ve seen around with the autocomplete Widget since the syntax is $(‘selector’).autocomplete
Can someone please help?
This is the edit.js.erb file:
$("#activity_form").html("<%= escape_javascript(render(:partial => "form"))%>");
This is my jQuery code to bind the autocomplete widget to my text field.
jQuery ->
$('[type="text"][name*="[geocode_location]"]').autocomplete
source: (request, response) ->
$.ajax
url: "http://ws.geonames.org/searchJSON"
dataType: "jsonp"
data:
featureClass: "P"
style: "full"
maxRows: 12
name_startsWith: request.term
success: (data) ->
response $.map(data.geonames, (item) ->
label: item.name + ((if item.adminName1 then ", " + item.adminName1 else "")) + ", " + item.countryName
value: item.lat + ", " + item.lng
)
minLength: 2
open: ->
$(this).removeClass("ui-corner-all").addClass "ui-corner-top"
close: ->
$(this).removeClass("ui-corner-top").addClass "ui-corner-all"
focus: (event, ui) ->
event.preventDefault()
$(this).val ui.item.label
select: (event, ui) ->
event.preventDefault()
$(this).val ui.item.label
$(this).siblings('[name*="[geocode_ll]"]').val ui.item.value
I read here about how there are 6 custom events that each Rails Ajax call can bind to, including ajax:success which is fired anytime there is a successful ajax request.
http://net.tutsplus.com/tutorials/javascript-ajax/using-unobtrusive-javascript-and-ajax-with-rails-3/
So I did $(this).bind “ajax:success” which allows $(this) which is the entire window in this case, to fire off some other functions after any “ajax:success” event.
So, I ended up doing this: