I've created an array using php which I've then json encoded
$json_array = json_encode($newarray);
In my jquery, the encoded array seems to be formed OK (i think??) but when I try and use the json data - nothing happens? I'm expecting the textbox to autocomplete.
The funny thing is - it works if I use arraytxt2, but not arraytxt1 (the one created via json_encode).
Any ideas as to why arraytxt1 is not working?? Thanks in advance.
$(document).ready(function () {
var arraytxt1 = [{
"equipmentid": "1",
"equipmentmake": "Baxi"
}, {
"equipmentid": "2",
"equipmentmake": "Baxi"
}];
var arraytxt2 = [{
"id": "1",
"label": "aa"
}, {
"id": "2",
"label": "bb"
}, {
"id": "3",
"label": "bbbb"
}, {
"id": "4",
"label": "abab"
}, {
"id": "5",
"label": "cab"
}];
$("#txt1").autocomplete({
source: arraytxt1,
minLength: 1,
select: function (event, ui) {
$("#txt2").val(ui.item.equipmentid);
}
});
});
-
1Please take the time to format your code properly. It makes it much easier for you, and others, to understand.Rory McCrossan– Rory McCrossan2015年11月12日 22:10:01 +00:00Commented Nov 12, 2015 at 22:10
-
Both arraytxt1 and arraytxt2 are valid JSON (jsonlint.com). Something must be amiss in the code you didn't provide. Do you see any errors in your developer console or is the value of #txt2 just not updating?robbymarston– robbymarston2015年11月12日 22:18:32 +00:00Commented Nov 12, 2015 at 22:18
-
Is the data for arraytxt1 in this code just for example? or are you fetching the json data from php in the javascript? If the latter then you might need to convert the JSON string into the array format you have here.spaniol6– spaniol62015年11月12日 22:20:18 +00:00Commented Nov 12, 2015 at 22:20
-
Sorry @Rory McCrossan first time posting and simply copied and pasted the code. Apologies.ChrisOrrick– ChrisOrrick2015年11月14日 10:56:59 +00:00Commented Nov 14, 2015 at 10:56
-
Hi @spaniol6 yes the second array was simply to test. The fields in the first array are coming from the database via php then encoded. Thanks for your input. Appreciate it. ChrisChrisOrrick– ChrisOrrick2015年11月14日 11:16:27 +00:00Commented Nov 14, 2015 at 11:16
1 Answer 1
The correct keys for autocomplete's array objects are label
and value
. The value property might not be needed in your case.
https://api.jqueryui.com/autocomplete/#option-source
Try:
var arraytxt1 = [{
"equipmentid": "1",
"label": "Baxi"
}, {
"equipmentid": "2",
"label": "Baxi"
}];