user1736786
user1736786

Reputation: 55

jQuery UI autoComplete with external JSON file

I'm trying to write a jQuery UI autocomplete by reading an external file (i.e. data.json). The code works fine when I try to read it from an array but if I try to read it from an external file, it doesn't work anymore!?! Not sure why!!

Here's my code:

http://plnkr.co/edit/LPqBGyocpswPrEzjb1Nq?p=preview

OR

<!doctype html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <title>jQuery UI Autocomplete functionality</title>
      <link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
      <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
      <script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
      <script>
         $(function() {
            $( "#autocomplete1" ).autocomplete(
            {
                source:"data.json",
                select: function( event, ui ) {
                    $( "#autocomplete1" ).val( ui.item.code + " - " + ui.item.label );
                    return false;
                }
            }).data( "autocomplete" )._renderItem = function( ul, item ) {
                return $( "<li></li>" )
                    .data( "item.autocomplete", item )
                    .append( "<a>" + item.code + " - " + item.label + "</a>" )
                    .appendTo( ul );
                };      

        });        
      </script>
   </head>

   <body>
      <input type="text" id="autocomplete1" size=40/>
   </body>
</html>

/********************************************************/

Here's the data.json file:

{   
    {
        "code":"YOO",
        "label":"Oshawa",
        "country":"Canada",
    },
    {
        "code":"YOW",
        "label":"Ottawa Macdonald-Cartier International",
        "city":"Ottawa",
    },
    {
        "code":"YOH",
        "label":"Oxford House",
        "city":"Oxford House",
    } 
}

tks

Upvotes: 0

Views: 5703

Answers (1)

T J
T J

Reputation: 43156

From docs:

Source Type: Array or String or Function( Object request, Function response( Object data ) )

                                               Default: none; must be specified

Defines the data to use, must be specified. Independent of the variant you use, the label is always treated as text. If you want the label to be treated as html you can use Scott González' html extension. The demos all focus on different variations of the source option - look for one that matches your use case, and check out the code.

Multiple types supported:

  • Array: An array can be used for local data. There are two supported formats:

    • An array of strings: [ "Choice1", "Choice2" ]
    • An array of objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ]

    The label property is displayed in the suggestion menu. The value will be inserted into the input element when a user selects an item. If just one property is specified, it will be used for both, e.g., if you provide only value properties, the value will also be used as the label.

  • String: When a string is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data. It can be on the same host or on a different one (must provide JSONP). The Autocomplete plugin does not filter the results, instead a query string is added with a term field, which the server-side script should use for filtering the results. For example, if the source option is set to "http://example.com" and the user types foo, a GET request would be made to http://example.com?term=foo. The data itself can be in the same format as the local data described above.

  • Function: The third variation, a callback, provides the most flexibility and can be used to connect any data source to Autocomplete. The callback gets two arguments:

    • A request object, with a single term property, which refers to the value currently in the text input. For example, if the user enters "new yo" in a city field, the Autocomplete term will equal "new yo".

    • A response callback, which expects a single argument: the data to suggest to the user. This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data. It's important when providing a custom source callback to handle errors during the request. You must always call the response callback even if you encounter an error. This ensures that the widget always has the correct state.

    When filtering data locally, you can make use of the built-in $.ui.autocomplete.escapeRegex function. It'll take a single string argument and escape all regex characters, making the result safe to pass to new RegExp().

You're specifying a string. The key point here is:

The Autocomplete plugin does not filter the results, instead a query string is added with a term field, which the server-side script should use for filtering the results. For example, if the source option is set to "http://example.com" and the user types foo, a GET request would be made to http://example.com?term=foo. The data itself can be in the same format as the local data described above.

The string if meant to specify a url to hit, which returns the data in specified format.

jQueryui autocomplete doesn't directly accept a JSON, hence your code isn't working. You should specify a valid data source.

Their plugin, their rules :)

Related:

Upvotes: 1

Related Questions