I have a problem with Jquery Autocomplete. My code work perfectly but when I change the Data Source, it is not working.
Here is my code and work perfectly.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Seach Autocomplete</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
</head>
<body>
<label for="field_id">ID</label>
<input id="field_id" type="text" style="width: 200px;">
<label for="field">Search</label>
<input id="field" type="text" style="width: 200px;">
</body>
</html>
<script>
$(function() {
var data = [
{
"id": "17",
"value": "Albania",
"label": "Albania"
},
{
"id": "18",
"value": "Algeria",
"label": "Algeria"
},
{
"id": "20",
"value": "American Samoa",
"label": "American Samoa"
}
];
$("#field").autocomplete({
source: data,
minLength: 1,
select: function(event, ui) {
$("#field_id").val(ui.item.id);
}
});
});
</script>
But if I change the data to this below is not working and the result not show up. Here is the data and not working:
{
"id": 298,
"city_name": "Jakarta Timur",
"province_name": "DKI Jakarta"
},
{
"id": 299,
"city_name": "Kabupaten Tangerang",
"province_name": "Banten"
},
{
"id": 230,
"city_name": "Jakarta Timur",
"province_name": "DKI Jakarta"
}
CodePudding user response:
Based on documentation it's not working because should be an array of objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ]
. You can use the following code to fix your problem:
$(function() {
var data = [
{
"id": 298,
"city_name": "Jakarta Timur",
"province_name": "DKI Jakarta"
}
];
data.forEach(function(obj) {
let keys = Object.keys(obj);
obj.label = obj[keys[1]];
obj.value = obj[keys[2]];
delete obj[keys[1]];
delete obj[keys[2]];
});
$("#field").autocomplete({
source: data,
minLength: 1,
select: function(event, ui) {
$("#field_id").val(ui.item.id);
}
});
});