Created
November 17, 2015 02:56
-
-
Save AlexandrBasan/ba1152dfa8a5ce1e19be to your computer and use it in GitHub Desktop.
Rails autocomplete by data from URL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def index | |
@data = Company.all | |
respond_to do |format| | |
format.html | |
format.json { render :json => @data.to_json } | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<% @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
http://stackoverflow.com/questions/3188157/how-to-set-up-jquery-ui-autocomplete-in-rails