<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script>
<style type="text/css">
.select2-container{
width: 100%!important;
}
.select2-search--dropdown .select2-search__field {
width: 98%;
}
</style>
<title>Document</title>
</head>
<body>
<div class="container">
<h1>Load JSON Data To Select2 JQuery Plugin</h1>
<select class="js-data-example-ajax" style="width: 300px">
<option value="">Nhập từ khóa tìm kiếm</option>
</select>
<script type="text/javascript">
$(document).ready(function() {
$(".js-data-example-ajax").select2({
ajax: {
url: 'https://api.github.com/search/repositories',
dataType: 'json',
type: "GET",
delay: 250,
data: function(params) {
return {
q: params.term
};
},
minimumInputLength: 1,
placeholder: "Nhập từ khóa tìm kiếm",
processResults: function(data) {
var res = data.items.map(function(item) {
return { id: item.id, text: item.name };
});
return {
results: res
};
}
},
});
});
</script>
</body>
</html>