Fetching Bank List using Choices.js and Fetch API
This code snippet fetches a list of banks using the Fetch API and populates a dropdown using Choices.js. It provides users with a way to select a bank from the dropdown.
For a working example and a playground to test out the code, you can visit the Codepen demo here
#Usage and example
Include the Choices.js library in your project.
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/choices.js/public/assets/styles/choices.min.css" /><script src="https://cdn.jsdelivr.net/npm/choices.js/public/assets/scripts/choices.min.js"></script>
code examples
#HTML
<label for="banks"> bank list (Fetch API)</label><select class="form-control" name="banks" id="banks"> <option value=""> Select bank </option></select>
#Javascript
The JavaScript code performs the following operations:
- Initializes a Choices.js instance for the dropdown element.
- Fetches bank data from nubapi.com Endpoint and populates the Choices.js dropdown.
- Sets a default choice by its value OR a custom value.
document.addEventListener('DOMContentLoaded', function() { const selectElement = document.getElementById('banks'); const bankList = new Choices(selectElement, { allowHTML: false, searchPlaceholderValue: 'Search for a bank', }); bankList.setChoices(function() { return fetch( 'https://nubapi.com/bank-object' ) .then(function(response) { return response.json(); }) .then(function(data) { return data.map(function(data) { return { label: data.label, value: data.value }; }); }); }); bankList.setChoiceByValue(119); bankList.passedElement.element.addEventListener( 'change', // you can listen 'addItem' as alternate to change function(event) { //Log your seleted details console.log(event.detail.id); console.log(event.detail.value); console.log(event.detail.label); console.log(event.detail.customProperties); console.log(event.detail.groupValue); //Alternatively you can get the selected details anywhere from your //App using the below query selector console.log(document.getElementById('banks').value); console.log(document.getElementById('banks').innerText); }, false, ); });
#Event Listeners
The code listens for the change event on the Choices.js element and logs various details of the selected option.
For more information, please visit the official documentation of Choices.js