I need some help on how to implement a jquery-ui autocomplete in my Rails app.
I want to add autocompletion to a text field where the user can enter in a customer name. As there can be hundreds of customers, I will need to pull the suggested auto-completion values 'remotely', as in, from a table (at least this is what I understand).
The main point I am failing to understand is how to provide the suggested values to the autocompletion textbox. I have read the jquery-ui docs, but I seem to be a bit dense on this matter.
So what I am really after is an example of how I can get this to work in a Rails app, not necessarily a full description of how the javascript is built (that's what the jquery-ui team has done for me =) ).
For example, how do I prepare the data for the autocompletion, and how do I attach the autocompletion functionality to a textbox.
Well I never got an answer to my question above so I ended up having to figure it out for myself. I thought I should post the solution I came up with in case there are any other guys out there who are wondering the same thing.
First thing you should know is that this is my first experience with javascript, and I am just getting the hang of Rails. So by all means, feel free to edit, comment anywhere you feel I have gone wrong with this. Right or wrong at least I know that it functions the way I wanted it to.
I think the best way to show this is by example. So the following is how I got the autocomplete widget to work in my app. You can go ahead and put the following code in your app even if you don't understand what is happening, then we can go over how each part is working by example. After this you should have a grasp on how to modify it for your use or refractor it.
**INCLUDE JQUERY UI IN YOUR RAILS APP.**
Download a copy of the [jQuery UI][ui] and place jquery-ui-1.8.2.custom.min.js inside your /public/javascript directory. Also make sure you have a copy of jQuery itself and that this is also in the same folder.
Include the jQuery UI file and the jQuery file in your application.html.erb file like this.(you can name the files as you please as long as they match)
<%= javascript_include_tag 'jquery.min', 'jquery-ui-1.8.2.custom.min.js' %>
In your download of jQuery UI, you will have a folder that contains all of your CSS data. The name will vary based on the theme you chose, for example I chose the theme 'cupertino'. Place the entire folder containing your CSS data into '/public/stylesheets/'. Then include the CSS file in your application.html.erb like this.
<%= stylesheet_link_tag 'cupertino/jquery-ui-1.8.2.custom' %>
**EXAMPLE AUTOCOMPLETE JAVASCRIPT**
Now take the following chunk of code and place it in one of your 'new' views. You can use this in any view, but realize that I have literally taken it from an existing view belonging to a controller called 'links_controller', and it is pulling data from a 'people_controller'. Hopefully you know enough about Rails to work out what you need to change so this works for you.
-- Begin big chunk of code --
<script type="text/javascript">
$(function() {
// Below is the name of the textfield that will be autocomplete
$('#select_origin').autocomplete({
// This shows the min length of charcters that must be typed before the autocomplete looks for a match.
minLength: 2,
// This is the source of the auocomplete suggestions. In this case a list of names from the people controller, in JSON format.
source: '<%= people_path(:json) %>',
// This updates the textfield when you move the updown the suggestions list, with your keyboard. In our case it will reflect the same value that you see in the suggestions which is the person.given_name.
focus: function(event, ui) {
$('#select_origin').val(ui.item.person.given_name);
return false;
},
// Once a value in the drop down list is selected, do the following:
select: function(event, ui) {
// place the person.given_name value into the textfield called 'select_origin'...
$('#select_origin').val(ui.item.person.given_name);
// and place the person.id into the hidden textfield called 'link_origin_id'.
$('#link_origin_id').val(ui.item.person.id);
return false;
}
})
// The below code is straight from the jQuery example. It formats what data is displayed in the dropdown box, and can be customized.
.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.person.given_name + "</a>" )
.appendTo( ul );
};
});
</script>
<h1>New link</h1>
<% form_for(#link) do |f| %>
<%= f.error_messages %>
<!-- Place the following text fields in your form, the names are not important. What is important is that they match the names in your javascript above -->
<p>
Select which person you want to link:<br />
<!-- This is the textfield that will autocomplete. What is displayed here is for the user to see but the data will not go anywhere -->
<input id="select_origin"/>
<!-- This is the hidden textfield that will be given the Persons ID based on who is selected. This value will be sent as a parameter -->
<input id="link_origin_id" name="link[origin_id]" type="hidden"/>
</p>
<!-- end of notes -->
<p>
<%= f.label :rcvd_id %><br />
<%= f.text_field :rcvd_id %>
</p>
<p>
<%= f.label :link_type %><br />
<%= f.text_field :link_type %>
</p>
<p>
<%= f.label :summary %><br />
<%= f.text_area :summary %>
</p>
<p>
<%= f.label :active %><br />
<%= f.check_box :active %>
</p>
<p>
<%= f.submit 'Create' %>
</p>
<% end %>
-- End Big Chunk of Code --
Okay now to connect the dots.
**PROVIDE DATA FOR AUTOCOMPLETE TO USE AS SUGGESTIONS**
Lets start by connecting up some data that the autocomplete textfield can display in the drop down suggestions. The format we will be using is JSON, but don't worry if you are not familiar with it ... neither am I =). It is good enough to know that it is a way to format text so that other parts of yours/other applications can use it.
The data the textfield will need for the autocomplete is specified in the 'source:' option. Because we want to send a list of peoples names and their ID to the autocomplete we will put the following as the source.
source: '<%= people_path(:json) %>'
The rails helper above will translate to a string "/people.json". You do not need to create a page at "/people.json". What you do need to do is tell your people_controller what to do when it receives a request for /people with the .json format. Put the following into your people_controller:
def index
# I will explain this part in a moment.
if params[:term]
#people = Person.find(:all,:conditions => ['given_name LIKE ?', "#{params[:term]}%"])
else
#people = Person.all
end
respond_to do |format|
format.html # index.html.erb
# Here is where you can specify how to handle the request for "/people.json"
format.json { render :json => #people.to_json }
end
end
Now we have all the people in #people being sent to the autocomplete textfield. This brings up the very next point.
**FILTER DATA USED FOR AUTOCOMPLETE SUGGESTION, BASED ON INPUT**
How does the autocomplete textfield know how to filter the results based on what you type?
The autocomplete widget assigned to the textfield will send whatever you type into the textfield as a parameter to your source:. The parameter being sent is "term". So if you were to type "Joe" into the textfield, we would be doing the following:
/people.json?term=joe
That is why we have the following in the controller:
# If the autocomplete is used, it will send a parameter 'term', so we catch that here
if params[:term]
# Then we limit the number of records assigned to #people, by using the term value as a filter.
#people = Person.find(:all,:conditions => ['given_name LIKE ?', "#{params[:term]}%"])
# In my example, I still need to access all records when I first render the page, so for normal use I assign all. This has nothing to do with the autocomplete, just showing you how I used it in my situation.
else
#people = Person.all
end
Now that we have limited the number of records assigned to #people based on what is typed into the autocomplete textfield, we can now turn that into JSON format for the autocomplete suggestions.
respond_to do |format|
format.html # index.html.erb
format.json { render :json => #people.to_json }
end
Now, just review the comments inside the "Big Chunk of Code" which should explain the rest of how this ties together.
At the end you should have a textfield on your page that acts as the autocomplete and a hidden field that will send the ID in a parameter to your controller.
**CUSTOMIZE YOUR OWN AUTOCOMPLETE**
Once you understand the above and you want to modify it for your use, you should know that the format JSON returned from your controller looks like this:
[{"person":{"id":1,"given_name":"joe","middle_name":"smith","family_name":"jones","nationality":"australian"}}]
The way to access the different values from the JSON string in your javascript in this case would be:
ui.item.person.name_of_some_attribute_such_as_given_name
Pretty, simple. A lot like accessing an ActiveRecord attribute in Rails.
One last note. I spent a lot of time looking for a different way to supply the hidden value, as I thought this function should have been built into the jquery widget. However, this is not the case. It is clearly shown in the official jQuery example that the way to send a different value then selected as a parameter, is to use a hidden field.
Dale
[ui]:http://jqueryui.com/download
jQuery 1.9/1.10 removed the key autocomplete and added uiAutocomplete
.data("uiAutocomplete") instead of .data("autocomplete")
After modifying to above,it worked for me.
Dale's Answer is quite the tutorial. One thing to note is that using your first query, the datasource will only return matches beginning with the string you type. If you want search anywhere in the word, you need to change:
#people = Person.find(:all,:conditions =>
['given_name LIKE ?', "#{params[:term]}%"])
to
#people = Person.find(:all,:conditions =>
['given_name LIKE ?', "%#{params[:term]}%"])
(added an extra % to the query)
I basically followed Dale's advice below but my controller and js files were slightly diff- his version was giving me issues for some reason (maybe bc of jquery updates)
Context: I'm trying to autocomplete names of DJs typed in by users - also a newb
DJs Controller
class DjsController < ApplicationController
def index
if params[:term]
#djs = Dj.is_dj.where('lower(name) LIKE ?', "%#{params[:term].downcase}%")
respond_to do |format|
format.html
format.json { render :json => #djs.map(&:name) }
end
end
end
end
html.erb file
<script type="text/javascript">
$(function() {
$('#select_origin').autocomplete({
source: '<%= djs_path(:json) %>'
})
$('.submit-comment').click(function(){
var dj_name = $('#select_origin').val();
$('#link_origin_id').val(dj_name);
})
})
</script>
This is a great help.
In addition to it in case if you need to fetch url of image of user, it might not be possible with to_json. For that add the following code in model.
def avatar_url
avatar.url(:thumb)
end
And then in controller instead of to_json use as_json
respond_to do |format|
format.json {render :json => #users.as_json(:only => [:id,:name,:username], :methods => [:avatar_url]) }
end
It's important to note that if your 'source' is relatively small, for example 50 elements, the implementation should be different (and a lot simpler). It is mentioned in the fourth paragraph of the official doc:
https://api.jqueryui.com/autocomplete/
When using local data all you need to do is obtain the data and pass it to the autocomplete method, and it will do the filtering for you. You don't need to go back and forth to the server every time a term es entered.
function filterByTags(tags) {
$("#stories-filter").autocomplete({
source: tags,
autoFocus: true
});
}
$("#stories-filter").click(function() {
$.ajax({
dataType: 'json',
method: 'GET',
url: 'tags/index',
data: $(this).data('project-id'),
success: function (response) {
if(response.success) {
var tags = response.data.tags;
filterByTags(tags);
}
},
error: function (response) {
if(response.status === 422) {
var $errors = 'There are no tags in this project',
$errorsContainer = $('.error-container');
$errorsContainer.append($errors);
$errorsContainer.show();
}
}
});
});
Since this is old, but google still comes here, a small note about the main answer, which is essentially good, but some things have changed:
see answer about jquery having changed .data("uiAutocomplete") to .data("autocomplete")
Also i would recommend a separate route on the resource collection that just handles json
use rabl to create smaller json (or pluck for larger models)
ilike , not like, for case insensitive
the % in front, so the search is not just start_with.
valiable traversal in the methods, like item.person.name are just item.name (so drop the .person)
use coffee (in haml)
use a limit, and where as in: Person.where('given_name ilike ?', "%#{params[:term]}%").limit(20)
Related
I'm working on an forum-type app in Rails v 4.2.5. My index page is a list of all the questions being discussed in the application and they are default sorted by the created_at date. I am also using the Kaminari gem to paginate all of the questions (25 per page). I originally had my app set up like this:
Questions Controller:
def index
#questions = Question.order(:created_at).page params[:page]
end
Index View:
# I render a partial that iterates through the questions list to display
# the title of the questions, then I include the paginate code below.
<div class="pagination">
<%= paginate #questions %>
</div>
I eventually decided I wanted users to be able to sort the questions by different criteria (e.g., by total amount of upvotes, by total amount of responses for a question, and by recently asked questions). Right now, you can click a link corresponding to the type of sort you want and it will AJAX the new sorted list (a partial) onto the page. However, when I do this, the pagination does not work and when I click to see the second page of the results, everything becomes unsorted.
Index View with Sort Links:
<div class="sort_selection">
<h3> Sort By: </h3>
<%= link_to "By Upvotes", "/questions/top?sort=votes", class: "question_sort_link" %>
<%= link_to "Answers Provided", "/questions/top?sort=answers", class: "question_sort_link" %>
<%= link_to "Recently Asked", "/questions/top?sort=recent", class: "question_sort_link" %>
</div>
Index Controller:
def top
case params[:sort]
when "votes"
#questions = Question.sort_by_votes #sort_by_votes is a method in my Question model that performs a SQL query
when "answers"
#questions = Question.where.not(answers_count: nil).order(answers_count: :desc).limit(25)
when "recent"
#questions = Question.order(created_at: :desc).limit(25)
end
render partial: 'questions_list', layout: false
end
Javascript AJAX
$(document).on("click", ".question_sort_link", function(event){
event.preventDefault();
$.ajax({
method: "get",
url: $(this).attr("href")
}).done(function(sorted){
$('.questions_show_sorted').replaceWith(sorted);
});
});
I fooled around with the placement of the <%= paginate #questions %> in the view, as well as removed the 25 limit in my controller and added .page params[:page] after all of the queries in the Top route but I still cannot get the pagination to work after I've AJAX'ed a sorted list onto the page. Does anyone have any suggestions?
When you are switching pages the data about sorting is lost, because you are reloading site with different parameters. You can either try to pass this data (the column you are going to sort, and info is it asc or desc) to the new page, and sort it before loading, or paginate it using AJAX (but that means loading everything at the first load). I can't tell about the "pagination does not work problem", because I don't know what you mean.
In general, this thing you are trying to do is rather complicated, and there is no simple solution for that. There is a library for JS called Datatables that (in theory) makes it easier. There is another library called jQ-Bootgrid, and a ruby gem called "Smart listing".
I think you need to provide the pagination links in your ajax response and replace them in your javascript callback.
I assume that you return html rather than json, which will make this a bit awkward. Perhaps you could build up a json response with pagination links and html content
{
next: /list?page=3,
prev: /list?page=1,
content: "<ul>
<li>foo</li>
<li>bar</li>
</ul>"
}
I am trying to make a text box that displays a list of sorted users that sorts per every typed letter. From there the person can add the user as a collaborator. The result should be kind of like facebook's search feature when you are searching to add new friends. When I press a key I see a new 500 internal server error in the network section of the browsers console. Here is a snippet of the response:
<h1>
NoMethodError
in CollaborationsController#collaboration_search
</h1>
</header>
<div id="container">
<h2>undefined method `[]' for nil:NilClass</h2>
So I think the ajax is getting fired to the server but there is something wrong with the controller. Here is my code for the view, views/collaborations/_new.html.erb:
<%= form_for [wiki, collaboration] do |f|%>
<div class = "col-md-8">
<div class = "form-group">
<%= f.label :user_name %>
<%= f.text_field :user_name, class: 'form-control', placeholder: "Enter name" %>
</div>
<div class = "form-group">
<%= f.submit class: 'btn btn-success' %>
</div>
</div>
<%= #users_by_name.to_a %>
</div>
</div>
</div>
<%end%>
where the form above is a partial. The ajax is written in javascripts/collaborations.js:
$(document).ready(function()
{
// alert(1);
$('#collaboration_user_name').on('keyup', function() {
// text = $(this).val();
// alert(text);
$.ajax({ url: "/collaborations",
beforeSend: function( xhr ) {
xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
}
}).done(function( data ) {
if( console && console.log ) {
console.log( "Sample of data:", data.slice( 0, 100 ) );
//alert()
}
});
});
});
Here is the collaboration#search_collaboration action within the collaborations controller:
def collaboration_search
name_search = params[:collaboration][:user_name].to_s
#users_by_name = User.where('name Like ?', "%#{params[:collaboration][:user_name]}%")
render json: #users_by_name.map do |user|
{ name: user.name, id: user.id}
end
end
And just for testing purposes I kept my collaborations/search_collaboration.js.erb very simple:
alert('hello');
however if someone can point me in the right direction for how to list the names of the users returned from the collaboration_search action that would be much appreciated!
The error seems to suggest that you're trying to index into something as a hash, when it is, in fact, nil:
undefined method `[]' for nil:NilClass
The [] refers to hash indexing -- such as params[:collaboration]. My immediate guess would be that you're not serving the params to this controller action in the format expected, so that params[:collaboration] is nil, and you're trying to index into that params[:collaboration][:user_name], provoking said error.
This jives with your current jQuery code, which doesn't send the data at all (where are you sending text as a parameter, either in the querystring or as a jQuery.ajax() param?), not to mention in that specific format.
You could either do something like this:
$.ajax({ url: "/collaborations?collaboration=#{text}",
#..etc
Or you could use the ajax function's data method to give it a parameter as a hash instead of just throwing it in the URL. The docs for that function should give you more information.
I'd strongly recommend the latter, as you expect nested hashes in your controller [:collaboration][:user_name], which is not easily supported in a querystring parameter.
To see what the parameters are coming in as, I suggest throwing something like this in your Ruby controller:
puts "PARAMS: #{params.inspect}"
That should go above anything causing an error. It will print out the params in your server log (the terminal tab where you typed rails server or rails s), so that you can see what the parameters are, and whether this hypothesis is accurate, and how to fix the problem.
As a final note, I don't think you're actually hitting your .js.erb file at all. Your action just returns a response to the jQuery ajax function. That response is in your function called on done(), and the response data is, in your current code, referred to as data. I'd alert that data once you've gotten past this error, to see how your controller is serializing things. And then, without that js.erb file, you can simply update the DOM with the results from the jQuery.
(Final note, I can't think of an occasion where you'd need to test for if console && console.log, and I'm not sure that test won't throw an error. I might be wrong, though.)
The UX Jargon for what you what you are trying to build is autocomplete dropdown or autocomplete combobox. It is actually a fairly complicated UI element that I wouldn't both programming from scratch. You should use a library like JQuery. JQuery is built into core Rails so I should just be a matter of including the right library. Here Is a sample of the element from JQuery.
http://jquery-ui.googlecode.com/svn/tags/1.8.7/demos/autocomplete/combobox.html
You can look at the source code using the browser development tools
Here is JQuery Autocomplete docs
http://jqueryui.com/autocomplete/
You can look at the code in you
Here is another implementation
http://www.jqwidgets.com/jquery-widgets-demo/demos/jqxcombobox/index.htm
I want to add auto-complete to my search bar. But when I submit the completed user I get this url :
/users?utf8=✓&search=Thomas
Instead of /users/23
My controller
#users = User.find(:all, :select=>'name').map(&:name)
The Javascript
<%= javascript_tag "var autocomplete_items = #{ #users };" %>
<script type="text/javascript">
jQuery(document).ready(function() {
$('#auto_complete').typeahead({source: autocomplete_items});
});
</script>
My form
<%= form_tag users_path, :method => :get do %>
<%= text_field_tag :search, params[:search], :id => "auto_complete" %>
<% end %>
Thanks for your help
From what I can glean from the Bootstrap docs, typeahead is only designed to do just that - type ahead of text. It just takes your input, sees if there's something in its source that matches the input and offers some alternatives for completing the input. If the user chooses an alternative, typeahead fills in the selected string.
So the only thing you get is a string in an input field.
Typeahead does not know how to construct a link like the one you need: /uses/23
Event if Bootstrap typeahead knew how to do that, you haven't provided it with the needed information since you're only providing it with the names of the users.
I think what you want to do is:
Send both user names and user paths to the view
Use some kind of autocomplete widget that can trigger a callback when an item is selected.
Use the callback to navigate to the selected user path when a user is selected
I'm not entirely familiar with Bootstrap's typeahead - you may be able to do this stuff with it.
But I argue for using something that's better documented, like jQuery UI:s autocomplete.
Im looking for an autocomplete ajax implementation for a textfield.
you type your city
it wil look for closest match in db as you type
as soon as it finds the city (partially search) it displays some options to choose from in format city, state you can pick one from the list and the textfield would contain " city, state"
What would be good ways of doing this in rails?
I think i need an autocomplete functionality for this with an ajax posting to the app
You can find the relevant JavaScript (assuming you're using JQuery) here, from there it's just a matter of setting up a controller action that returns some json and inserting the path to that action to the source: option.
So, very approximately, you'd do something like:
controller:
class CityController << ApplicationController
def lookup
cities = City.find_by_name(params[:city])
render :json => cities
end
end
view:
<%= form_tag do %>
<%= text_field_tag('city', :id => 'city_input') %>
<script type='text/javascript'>
$(function() {
$( "#city_input" ).autocomplete({
source: "<%= lookup_cities_path %>",
minLength: 2
});
});
</script>
<% end %>
I want to have a text box that the user can type in that shows an Ajax-populated list of my model's names, and then when the user selects one I want the HTML to save the model's ID, and use that when the form is submitted.
I've been poking at the auto_complete plugin that got excised in Rails 2, but it seems to have no inkling that this might be useful. There's a Railscast episode that covers using that plugin, but it doesn't touch on this topic. The comments point out that it could be an issue, and point to model_auto_completer as a possible solution, which seems to work if the viewed items are simple strings, but the inserted text includes lots of junk spaces if (as I would like to do) you include a picture into the list items, despite what the documentation says.
I could probably hack model_auto_completer into shape, and I may still end up doing so, but I am eager to find out if there are better options out there.
I rolled my own. The process is a little convoluted, but...
I just made a text_field on the form with an observer. When you start typing into the text field, the observer sends the search string and the controller returns a list of objects (maximum of 10).
The objects are then sent to render via a partial which fills out the dynamic autocomplete search results. The partial actually populates link_to_remote lines that post back to the controller again. The link_to_remote sends the id of the user selection and then some RJS cleans up the search, fills in the name in the text field, and then places the selected id into a hidden form field.
Phew... I couldn't find a plugin to do this at the time, so I rolled my own, I hope all that makes sense.
I've got a hackneyed fix for the junk spaces from the image. I added a :after_update_element => "trimSelectedItem" to the options hash of the model_auto_completer (that's the first hash of the three given). My trimSelectedItem then finds the appropriate sub-element and uses the contents of that for the element value:
function trimSelectedItem(element, value, hiddenField, modelID) {
var span = value.down('span.display-text')
console.log(span)
var text = span.innerText || span.textContent
console.log(text)
element.value = text
}
However, this then runs afoul of the :allow_free_text option, which by default changes the text back as soon as the text box loses focus if the text inside is not a "valid" item from the list. So I had to turn that off, too, by passing :allow_free_text => true into the options hash (again, the first hash). I'd really rather it remained on, though.
So my current call to create the autocompleter is:
<%= model_auto_completer(
"line_items_info[][name]", "",
"line_items_info[][id]", "",
{:url => formatted_products_path(:js),
:after_update_element => "trimSelectedItem",
:allow_free_text => true},
{:class => 'product-selector'},
{:method => 'GET', :param_name => 'q'}) %>
And the products/index.js.erb is:
<ul class='products'>
<%- for product in #products -%>
<li id="<%= dom_id(product) %>">
<%= image_tag image_product_path(product), :alt => "" %>
<span class='display-text'><%=h product.name %></span>
</li>
<%- end -%>
</ul>