views:

459

answers:

2

I'm using this jquery autocomplete plug-in with rails: http://docs.jquery.com/Plugins/Autocomplete

I can't figure out how to format my results, both in my Rails controller and in my javascript file.

I have something like this in my controller...

@query = params[:q].downcase
@json = User.all(:login => /^#{@query}/)
respond_to do |format|
  format.js  { render :json => @json.to_json(:only => "login"), :layout => false }  
end

And then this in my script.js file...

    $("#form").autocomplete('/url', {
    width: 320,
    dataType: 'json',
    highlight: false,
    scroll: true,
    scrollHeight: 300
    })

But I can't figure out how to parse the data, so my autocomplete just gets a raw array of all my results at once.

How do I process the JSON in the script.js file and/or in my controller for it to work?

A: 

According to the documentation for that plugin, there is no dataType option. You might also be mixing config options from one fork of the plugin with source from another fork.

Have you tried the default (pipe-delimited, if my memory serves me correctly) format for the suggestion data fetched from the server?

BTW, I did find this fork here which adds JSON support to the autocomplete plugin.

Justin Grant
A: 

I actually discovered a JSON example in the Demo. It looks like this:

    function format(user) {
        return user.login + " (" + user.name + ")";
    }
    $("#login").autocomplete('/url', {
        multiple: false,
        delay: 100,
        dataType: "json",
        parse: function(data) {
            return $.map(data, function(row) {
                return {
                    data: row,
                    value: row.login,
                    result: row.login
                }
            });
        },
        formatItem: function(item) {
            return format(item);
        }
    }).result(function(e, item) {
        $("#content").append("<p>selected " + format(item) + "</p>");
    });
});
Michael Waxman