I have the following hard coded json,
var dataLocality = [
{ "label": "Arwen" },
{ "label": "Bilbo Baggins" },
{ "label": "Boromir" },
{ "label": "Frodo Baggins" },
{ "label": "Peregrin Pippin Took" },
{ "label": "Samwise Gamgee" }
];
Which I use to populate an autocomplete textbox with the following script,
$(function () {
$("#locality").autocomplete(
{
source: dataLocality
})
});
I now have a text file that is dynamically updated via my app named dataLocality.text which i'm able to load and view in an alert box with this code,
function codeAddress() {
jQuery.get('http://localhost/project/jSonDocs/dataWhat.txt', function (data) {
var dataLocality = data;
alert(dataLocality);
});
}
window.onload = codeAddress;
But I can't seem to work out how to get the data from var dataLocality
to source: dataLocality
The data in my text doc looks like this,
[
{ "label": "Arwen" },
{ "label": "Bilbo Baggins" },
{ "label": "Boromir" },
{ "label": "Frodo Baggins" },
{ "label": "Peregrin Pippin Took" },
{ "label": "Samwise Gamgee" }
];
Assuming you're using the jQueryUI autocomplete method, you can provide the URL of the JSON to the source
method and it will retrieve it for you automatically. Try this:
$("#locality").autocomplete({
source: 'http://localhost/project/jSonDocs/dataWhat.txt'
});
If you still prefer to retrieve the JSON manually (if you need to change the source after initialisation for example) then you can achieve it like this:
function codeAddress() {
jQuery.get('http://localhost/project/jSonDocs/dataWhat.txt', function (data) {
$('#locality').autocomplete('option', 'source', data);
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With