2

I am having some trouble getting autocomplete to work specifically with a json file. It giving following error whenever something is entered in the text box

url is undefined

following is my jQuery code

$(document).ready(function() {
$('#autocomplete').autocomplete({
    minChars: 1,
    source: function(request, response) {
            var url='dataa.json';

        $.getJSON(url,{term: request.term},function(data){

            response($.map(data.ledgers, function(item) {
            return item.value;
        }));
    })
    }
});
});

and the JSON

{
"ledgers": 
[
{
    "id":"2001",
    "name":"Bharat"
},
{
    "id":"2003",
    "name":"Gaurav"
},
{
    "id":"2002",
    "name":"Pankaj"
},
{
    "id":"2022",
    "name":"Purchase"
},
{
    "id":"2007",
    "name":"Ram"
},
{
    "id":"2008",
    "name":"Ramesh"
},
{
    "id":"2009",
    "name":"Suresh"
}
]}
Nitin Kabra
  • 3,146
  • 10
  • 43
  • 62
  • I prepared page with the code you provided and it works. Tried in Chrome, not sure whether other browser will make any difference. Did you try use this script in isolation from your main app as I did? – Tomek Nov 03 '12 at 11:50
  • your code doesn't throw any error – rajesh kakawat Nov 03 '12 at 12:22

2 Answers2

2

Your JSON file format needs to contain value or label (or both). Change name to value and it should work fine.

$('#autocomplete').autocomplete({
    minChars: 1,
    source: function(request, response) {
            var url='dataa.json';

        $.getJSON(url,{term: request.term},function(data){
            response($.map(data.ledgers, function (value, key) {
                return {
                    label: value,
                    value: key
                };
            }));
        })
    }
});
Community
  • 1
  • 1
chridam
  • 100,957
  • 23
  • 236
  • 235
0

Try adding 'use strict'; at the top of your $(document).ready(). That may point out what the problem is...

return item.value;

item does not have a value, try returning id or name, which it does have.

Community
  • 1
  • 1
pete
  • 24,141
  • 4
  • 37
  • 51