Last active
November 24, 2024 14:27
-
-
Save devkabir/692f06c252459302600b70bdb94e3170 to your computer and use it in GitHub Desktop.
Select2 Lazy Loading
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" /> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0" /> | |
| <title>Select2 Lazy Loading</title> | |
| <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> | |
| <link | |
| href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" | |
| rel="stylesheet" | |
| /> | |
| <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script> | |
| </head> | |
| <body> | |
| <select id="lazy-load-select" style="width: 100%"></select> | |
| <script> | |
| $(document).ready(function () { | |
| $("#lazy-load-select").select2({ | |
| placeholder: "Select an option", | |
| ajax: { | |
| url: "http://localhost:3000/v1beta/accountSummaries", | |
| data: function (params) { | |
| // Retrieve nextPageToken from local storage if available | |
| const nextPageToken = localStorage.getItem("nextPageToken"); | |
| return { | |
| pageToken: nextPageToken || null, // Send nextPageToken if available | |
| pageSize: 5, // Fixed page size | |
| }; | |
| }, | |
| processResults: function (data, params) { | |
| console.log("Received nextPageToken:", data.nextPageToken); | |
| // Save the nextPageToken in local storage for subsequent requests | |
| if (data.nextPageToken) { | |
| localStorage.setItem("nextPageToken", data.nextPageToken); | |
| } else { | |
| // Clear the token if no more pages | |
| localStorage.removeItem("nextPageToken"); | |
| } | |
| // Convert API response into Select2-compatible format | |
| const results = data.accountSummaries.map((account) => { | |
| if (!account.propertySummaries.length) { | |
| return { | |
| id: account.account, | |
| text: account.displayName, | |
| }; | |
| } | |
| return { | |
| text: account.displayName, | |
| children: account.propertySummaries.map((property) => ({ | |
| id: property.property, | |
| text: property.displayName, | |
| })), | |
| }; | |
| }); | |
| // Update params.page with the nextPageToken for subsequent requests | |
| params.page = data.nextPageToken || null; | |
| return { | |
| results: results, | |
| pagination: { | |
| more: !!data.nextPageToken, // Indicate if more data is available | |
| }, | |
| }; | |
| }, | |
| cache: true, | |
| }, | |
| minimumResultsForSearch: Infinity, | |
| }); | |
| }); | |
| </script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment