Reputation: 5430
I have Post table with title and content attributes. I want to make auto complete textfield where user are suggested by Post title. I am trying to add jquery auto-complete in my rails application. I am doing like this ..
controller (Adding Posts title in Array)--
@posttitle = []
Post.all.each do |g|
@posttitle << g.title
end
View --
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<%= text_field_tag :search, params[:search], :placeholder => "Search Religious Places...", :id=>"tags" %>
<script>
$(function() {
var availableTags = <%= @posttitle %>;
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
But its not showing any suggestion (auto-complete is not working). I don't know whats going wrong. Please help
Upvotes: 4
Views: 14036
Reputation: 907
Have you tried something like this:
<script>
var availableTags = <%= raw @posttitle %>;
$(function() {
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
Upvotes: 8
Reputation: 40277
If you want an array of items in Ruby to appear as a javascript array, you'll need to:
1) get it into a comma separated list of values 2) wrap each value in quotes 3) escape the value so that quotes do not cause javascript errors
If you want just the title:
controller:
@titles = Post.pluck(:title)
and then in your view:
<script>
$(function() {
var availableTags = [<%= @titles.map{|title| escape_javascript(title)}.join(", ") %>];
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
Upvotes: 1
Reputation: 3083
I think you should not use the ruby array in javascript. It will not evaluated as an array. Instead you can create the javascript array and use it as
<script>
$(function() {
var availableTags = new Array();
<% @posttitle.each do |post| %>
availableTags.push(<%= post %>);
<% end %>
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
Upvotes: 0