Created
January 9, 2022 21:31
-
-
Save miloskroulik/efdc2d6c187b2c84906059ccda001b2f to your computer and use it in GitHub Desktop.
Select2 AJAX mapy.cz example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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/[email protected]/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/[email protected]/dist/jquery.min.js"></script> | |
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script> | |
<script src="ajax.js"></script> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(".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