A Pen by Putu Robhi Sanjaya on CodePen.
Last active
December 21, 2022 07:38
-
-
Save robhi2031/fbda45f354d7a601a61dd3dce63fbe60 to your computer and use it in GitHub Desktop.
Using Select2 From Api Data With SortResponse
This file contains 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
<html> | |
<head> | |
<title>Using Select2</title> | |
<!-- Bootstrap CSS --> | |
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css"> | |
<!-- Select2 CSS --> | |
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" /> | |
</head> | |
<body> | |
<div class="jumbotron"> | |
<div class="container bg-danger"> | |
<div class="col-md-6"> | |
<label>Single Select2</label> | |
<select id="single" class="js-states form-control select2 w-100"></select> | |
</div> | |
<div class="col-md-6"> | |
<label>Multiple Select2</label> | |
<select id="multiple" class="js-states form-control select2 w-100" multiple> | |
</select> | |
</div> | |
</div> | |
</div> | |
<!-- jQuery --> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> | |
<!-- Select2 --> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script> | |
</body> | |
</html> |
This file contains 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
const loadGetDataDropDown = () => { | |
let urlApi = 'https://pokeapi.co/api/v2/berry'; | |
$.ajax({ | |
url: urlApi, | |
type: 'get', | |
dataType: 'json', | |
}).then(response => { | |
// console.log(response.results) | |
let sortedData = []; | |
$(".select2").html(''); | |
$.each(sortResponse(response.results), function (key, value) { | |
// let name = value.name | |
if(value.key=='name'){ | |
console.log(value.value); | |
$(".select2").append('<option value="' +value.value+ '">' +value.value+ '</option>'); | |
} | |
}); | |
$("#single").select2({ | |
placeholder: "Select a programming language", | |
allowClear: true | |
}); | |
$("#multiple").select2({ | |
placeholder: "Select a programming language", | |
allowClear: true | |
}); | |
}); | |
} | |
const sortResponse = (data) => { | |
var sorted = []; | |
$(data).each(function(k, v) { | |
for(var key in v) { | |
sorted.push({key: key, value: v[key]}) | |
} | |
}); | |
return sorted.sort(function(a, b){ | |
if (a.value < b.value) return -1; | |
if (a.value > b.value) return 1; | |
return 0; | |
}); | |
} | |
loadGetDataDropDown() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment