jquery ui autocomplete json
[
{
"coords": {
"lat": "52.65",
"lon": "90.08333"
},
"district": "Сибирский",
"name": "Абаза",
"population": 17111,
"subject": "Хакасия"
},
{
"coords": {
"lat": "53.71667",
"lon": "91.41667"
},
"district": "Сибирский",
"name": "Абакан",
"population": 165183,
"subject": "Хакасия"
}, ...
And such developments:
$( ".city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "https://raw.githubusercontent.com/pensnarik/russian-cities/master/russian-cities.json",
dataType: "json",
data: {
term: request.term
},
minLength: 1,
success: function( data ) {
//response( data );
response( $.map( data, function( key, value ) {
return {
label: key.name,
value: key.subject
}
}));
},
select: function( event, ui ) {
console.log();
}
});
}
});
<link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<input type="text" class="city"/>
<div id="res"></div>
Question: How to properly implement jquery ui autocomplete with a json file? How do I display the selected city inside a block, for example, in <div id="res"></div>
?
0
1 answers
The term
transfer by Ajax is used when filtering is performed on the server side, and the result is returned as possible variants of the complement. If you have a static file, then you first upload it, make mapping to the desired view, and specify the result as the source.
Something like this:
$(function(){
var url = "https://raw.githubusercontent.com/pensnarik/russian-cities/master/russian-cities.json";
$.getJSON(url, function(src){
var data = src.map(function(v){
return {
value: v.name,
label: v.name + " (" + v.subject + ")"
};
});
$("input").autocomplete({
source: data,
select: function(event, ui){
$("#res").text(ui.item.value);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<input type="text" class="city"/>
<div id="res"></div>
1
Author: teran, 2019-04-18 08:57:35