Skip to content

Instantly share code, notes, and snippets.

@AlexandrBasan
Created November 17, 2015 02:56
Show Gist options
  • Save AlexandrBasan/ba1152dfa8a5ce1e19be to your computer and use it in GitHub Desktop.
Save AlexandrBasan/ba1152dfa8a5ce1e19be to your computer and use it in GitHub Desktop.
Rails autocomplete by data from URL
def index
@data = Company.all
respond_to do |format|
format.html
format.json { render :json => @data.to_json }
end
end
<% @customer = Customer.find(1) %>
<%= f.number_field :company_id %>
<%= text_field_tag nil, '', :id => 'company', data: {autocomplete_source: customer_data_path(@customer, :format => :json)} %>
<script>
$(function () {
var $searchBox = $('#company');
$searchBox.autocomplete(
{
source: $('#company').data('autocomplete-source'),
focus: function (event, ui) {
$('#company').val(ui.item.company.first_name + ' ' + ui.item.company.last_name);
return false;
},
select: function (e, ui) {
e.preventDefault() // <--- Prevent the value from being inserted.
$(this).val(ui.item.company.first_name + ' ' + ui.item.company.last_name)
$('#company_id').val(ui.item.company.id)
}
}).data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
// For now which just want to show the person.given_name in the list.
.append("<a>" + item.company.first_name + ' ' + item.company.last_name + "</a>")
.appendTo(ul);
};
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment