Skip to content

Instantly share code, notes, and snippets.

@miloskroulik
Created January 9, 2022 21:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miloskroulik/efdc2d6c187b2c84906059ccda001b2f to your computer and use it in GitHub Desktop.
Save miloskroulik/efdc2d6c187b2c84906059ccda001b2f to your computer and use it in GitHub Desktop.
Select2 AJAX mapy.cz example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Select 2 AJAX demo</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css"/>
</head>
<body>
<form action="">
<select class="js-data-example-ajax form-control" style="min-width: 850px;"></select>
</form>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script src="ajax.js"></script>
</body>
</html>
$(".js-data-example-ajax").select2({
ajax: {
url: "https://api.mapy.cz/suggest/?count=5&enableCategories=1&category=municipality_cz,quarter_cz&lang=cs",
dataType: 'json',
delay: 250,
data: function (params) {
return {
phrase: params.term, // search term
//page: params.page
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
//params.page = params.page || 1;
var results = data.result;
var formattedResults = [];
results.forEach(function (item) {
item.id = item.userData.wikiId;
item.text = item.userData.suggestFirstRow;
formattedResults.push(item);
})
return {
results: formattedResults,
// pagination: {
// more: (params.page * 30) < data.total_count
// }
};
},
cache: true
},
placeholder: 'Vyhledej obec',
minimumInputLength: 3,
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
function formatRepo(repo) {
if (repo.loading) {
return repo.text;
}
return repo.userData.suggestFirstRow;
}
function formatRepoSelection(repo) {
return repo.wikiId || repo.text;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment