Skip to content

Instantly share code, notes, and snippets.

@gensart-x
Last active October 3, 2025 14:57
Show Gist options
  • Save gensart-x/1bdde10198f644aae1c40b613c4115dd to your computer and use it in GitHub Desktop.
Save gensart-x/1bdde10198f644aae1c40b613c4115dd to your computer and use it in GitHub Desktop.
Select2 AJAX common setup
$('#mySelect2').select2({
dropdownParent: $('#your-modal-id'),
placeholder: 'Search for an item', // text shown when nothing is selected
allowClear: true, // adds an “×” button to clear the selection (for non‐required selects)
minimumInputLength: 3, // require at least 3 character input before AJAX request
multiple: false, // single selection (set to true for multi-select)
width: 'resolve', // how to compute width: 'resolve' uses container’s width
// You can also use width: '100%' or a fixed width
ajax: {
url: '/api/items/search', // endpoint to fetch results
dataType: 'json', // data type expected from server
delay: 250, // delay in ms after user stops typing before sending request
cache: true, // whether to cache the responses
data: function (params) {
// this function is used to customize the query parameters sent to server
// params.term = the search string entered by user
// params.page = the page number (for pagination)
return {
q: params.term, // map to “q” parameter
page: params.page || 1, // map to “page”; default to 1
extra_param: 'foo' // any additional param you want to send
};
},
processResults: function (data, params) {
// transforms the server response to the format Select2 expects
// `data` is whatever your server returned (JSON)
// `params.page` is the page we requested
// Example: suppose your server returns something like:
// {
// items: [ { id: 1, name: 'A' }, { id: 2, name: 'B' } ],
// total_count: 50
// }
return {
results: data.items.map(function (item) {
return {
id: item.id,
text: item.name,
// you can include extra fields here (e.g. item.description) if you want
};
})
}
},
},
language: {
inputTooShort: function (args) {
return 'Please enter ' + (args.minimum - args.input.length) + ' or more characters';
},
noResults: function () {
return 'No results found';
},
searching: function () {
return 'Searching…';
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment