views:

6961

answers:

5

Am a bit confused here, what does the formatResult and formatItem do in the JQuery Autocomplete plugin?

I have a function that is returning a comma separated string (from Django), but my autocomplete function is unable to split the string into individual entries/rows, how can i achieve this using autocomplete functions?

e.g the returned result looks like this and this what autocomplete is showing :- ["one","oneTwo", "Onethree", "anotherOne"]

I want when showing in the autocomplete field to have it split like this:-

one
oneTwo
Onethree
anotherOne

I have a feeling i can use the formatResult and formatItem but i dont know how, there are no good examples out there !!

my code in the html template:

 function autoFill(){
           $("#tags").autocomplete("/taglookup/", {
     width: 320,
     max: 4,
     highlight: false,
     multiple: true,
     multipleSeparator: " ",
     scroll: true,
     scrollHeight: 300
         });
       }

Am using Dajango to process the GET request.

Gath

+10  A: 

formatItem formats an item for display in the dropdown list, while formatResult formats the item for display in the inputbox once it is selected.

By default, autocomplete expects to get data from the specified url formatted as:

foo|bar|baz|bing
zaz|ding|blop|grok

where each line is a row of data; each row being the data that it passes to formatItem and formatResult. You may want to take the path of least resistance and return data in the way it likes.

If you want to use data that doesn't fit autocomplete's assumptions, you'll need to use the (undocumented, as far as I can tell) parse option to identify a function to parse the results of your ajax request. It appears to me that your django view is returning an array rather than returning a formatted string. To format your array as jquery would like it:

return HttpResponse('|'.join(your_array), mimetype='text/plain')

Here is an example of doing autocomplete using non-standard autocomplete data (JSON):

<script type="text/javascript"> 
  format_item = function (item, position, length){ 
    return item.title; 
  } 

 // Handle data from ajax request 
 prep_data = function(data){ 
   tmp = $.evalJSON(data); 
   parsed_data = []; 
   for (i=0; i < tmp.length; i++) { 
     obj = tmp[i]; 
     // Other internal autocomplete operations expect 
     // the data to be split into associative arrays of this sort 
     parsed_data[i] = { 
        data: obj , 
        value: obj.isbn13, 
        result: obj.title 
     }; 
   } 
   return parsed_data 
 } 

 $(document).ready(function(){ 
   $("#fop").autocomplete({ 
          url : "{% url book-search %}", 
          // undocumented 
          parse: prep_data, 
          formatItem: format_item, 
          }); 
 }) 

</script>
vezult
Thanks for your post, it was very helpful!
David Carlson
I think it would be more clear if you changed your "foo|bar|baz" example data to mirror the book-search example from the JSON section.
David Carlson
I think you should more clearly highlight that your answer contains 2 different approaches (split it into 2 answers?)
David Carlson
Perhaps you could change "Here is an example of doing autocomplete using non-standard autocomplete data (JSON)" to simply "Here is an example of autocomplete using (JSON)"
David Carlson
I think it would be more clearl if the "undocumented" comment was moved from above the line to the right of the line or if it read something like ("replace the undocumented parse function implementation with one that can parse JSON data")
David Carlson
You may want to include a pointer to http://code.google.com/p/jquery-json/ near the line where your parse the JSON data "$.evalJSON(data)"
David Carlson
would be helpful to detail how to use formatResult as well
aronchick
A: 

Hi,

Well this is not an answer, just another question along the same lines.

I want to implement the jquery autocomplete using json and a php remote page. This is my setup:

JS code:

$("#searchstring").autocomplete("/items/getitemsforautocomplete", {

     parse: prep_data,
     formatItem: format_item
});

      prep_data = function(data){ 
    tmp = $.evalJSON(data); 
    parsed_data = []; 
    for (i=0; i < tmp.length; i++) { 
      obj = tmp[i]; 
      // Other internal autocomplete operations expect 
      // the data to be split into associative arrays of this sort 
      parsed_data[i] = { 
         data: obj , 
         value: obj.itemname, 
         result: obj.id
      }; 
    } 

    return parsed_data;
  }


      format_item = function (item, position, length){ 
      return item.itemname;

    }

this is what my php remote function returns:

[{"itemname":"Durum Mel","id":"146"},{"itemname":"Flormelis","id":"140"},{"itemname":"Fuldkornsmel","id":"194"},{"itemname":"Groft Rugmel","id":"170"},{"itemname":"Hvedemel","id":"8"},{"itemname":"Marmelade","id":"13"},{"itemname":"Mel","id":"179"},{"itemname":"Mel Fuldkornshvede","id":"126"},{"itemname":"Speltmel","id":"177"}]

I have Firebug activated and this is what it says about the server response:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

Array

I don't get any autocomplete suggestions.

What am I doing wrong? any idea ???anyone???

A: 

I have not been able to get formatMatch and formatResult to work so far. I am still working on the 'correct' way to use them. However, as a workaround you can use the parse option as follows. Just to be clear, in this example, formatItem and parse are functional while formatResult and formatMatch are not functional.

jQuery(function(){
   $('#profile-tabs_addresses_grid_b_a_PostalCode').autocomplete
('http://test.mydomain.com/locality/postalcodes/', {
       minChars:1,
       delay:400,
       cacheLength:100,
       matchContains:true,
       max:10,
       formatItem:function(item, index, total, query){
           return item.PostalCode + ': ' + item.Region + ', ' +
item.City + ', ' + item.Country;
       },
       formatMatch:function(item){
           return item.PostalCode;
       },
       formatResult:function(item){
           return item.PostalCode;
       },
       dataType:'json',
       parse:function(data) {
                       return $.map(data, function(item) {
                               return {
                                       data: item,
                                       value: item.PostalCode,
                                       result: item.PostalCode
                               }
                       });
               }});
});

here is the json data that comes back from the data url ( whitespace added for easier viewing ):

[
       {City:"St. Louis", Country:"USA", PostalCode:"63103", ID:3,
Region:"Missouri"},
       {City:"St. Louis", Country:"USA", PostalCode:"63109", ID:1,
Region:"Missouri"},
       {City:"St. Louis", Country:"USA", PostalCode:"63119", ID:2,
Region:"Missouri"}
]

When I type a 6 in the postal code box, it shows all three options properly formatted as:

63103: Missouri, St. Louis, USA
63109: Missouri, St. Louis, USA
63119: Missouri, St. Louis, USA

and when I select one the textbox receives just the selected postal code.

Michael
+1  A: 

Some helpful posts here! While I was working on a solution for handling json results with jquery.autocomplete, I came across this post which is a bang on example for jquery.autocomplete, asp.net MVC, and controller actions returning json results. Hope this can help someone else.

Cedar Teeth
A: 

Thanks people, vezult in particular !