New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changing Options Dynamically #2830
Comments
I thought there was a ticket for this, but I can't seem to find it. If there is time with Select2 4.0, this is on the list of things that we want to implement. |
Is it now possible to change options (add, remove) dynamically? What is the API for that? |
It is not currently possible to do this dynamically. We may look into this in the future, but for now it does not look like it will be making it into 4.0. The general idea of what would need to happen is...
Which probably isn't that difficult, but I currently do not have the time to investigate the drawbacks or alternatives. |
I have a working workaround (dirty add-hoc solution, but it works). var $select = $('#id_of_native_select');
// save current config. options
var options = $select.data('select2').options.options;
// delete all items of the native select element
$select.html('');
// build new items
var items = [];
for (var i = 0; i < ...; i++) {
// logik to create new items
...
items.push({
"id": ...,
"text": ...
});
$select.append("<option value=\"" + ... + "\">" + ... + "</option>");
}
// add new items
options.data = items;
$select.select2(options); |
+1 for a placeholder API |
+1 for native API to add/remove/modify items dynamically. Workaround i'm using below - function initSelect(){
$("#select").select2({
... options ...
});
}
....
$("#select").select2("destroy");
// possible loop
$("#select").append("<option value='1'>Text</option>");
initSelect(); |
The nature of dynamically changing content typically requires other methods anyways. I believe Select2 doesn't require a dynamic data method. Rather, a standard (example) added to the documentation of a basic dynamic data change would be a clear enough solution. Iterating @razakj function- var data = {
dataCat1 : [...],
dataCat2 : [...],
}
function changeData(dataCategory){
$(".selectDynamic").select2({
data: dataCategory,
...
});
}
$(".selectStatic").on( "change", function(){
$(".selectDynamic").select2("destroy");
$(".selectDynamic").html("<option><option>");
changeData( data[ $(this).val() ] );
});
changeData(data["dataCat1"]); |
+1 for this feature request. Obvious use-case is multiple tagging interfaces on the page, and a user adds a tag to one, it should appear as an option in the others. Destroying & re-creating the select2 instances causes a flash of unstyled content which is not optimal. We already have something like this, imagine if select2 had this capability: window.initSelect2Fields = function () {
$('[data-simple-select2]').select2();
$('[data-select2-taggings]').select2({
tags: true,
matcher: function (params, data) {
/* ... custom matcher ... */
}
}).on("select2:select", function(e){
$('[data-select2-taggings]').select2("addOption", e.params.data);
});
/* more custom select2 init code */
} To implement the suggested workaround (complete with FOSC), I'd have to break out the initialization of tagging interfaces to an inner init function, something like this: window.initSelect2Fields = function () {
$('[data-simple-select2]').select2();
var initSelect2Taggings = function() {
$('[data-select2-taggings]').select2({
tags: true,
matcher: function (params, data) {
/* ... custom matcher ... */
}
});
}
initSelect2Taggings();
$('[data-simple-select2]').on("select2:select", function(e){
$('[data-simple-select2]').append("<option id='"+e.params.data.id+"'>"+e.params.data.text+"</option");
$('[data-simple-select2]').select2("destroy");
initSelect2Taggings();
});
/* ... more custom select2 init code ... */
} Personally, I'm not sure it's worth the additional maintenance weight. |
+1 for this feature. It's common to alter the content of a dropdown dynamically and with the previous verion I had no problem. |
+1 for this feature as well. |
+1 |
Isn't it possible to make a workaround "query" function? If so, any drawbacks ?
I look at the docs but even thought i failed to make it work with the current version of select2, if anybody has an example would be ace. |
+1 |
I've open an issue on StackOverflow, I don't know if it's related. My workaround is ugly, and I would love to fix it. |
Just use change().
|
Thanks @renandecarlo |
|
+1 |
+1 Need a clean way to destroy and recreate. Using $.select2('destroy') then creating on the same element causes bugs to appear in the API. Bad news.... |
+1 The inability to dynamically change/disable options is definitely a major deal. |
Regards the API for doing dynamic loading: perhaps mimic the DataTables approach and make the
As I see it, this requires the dynamic data to come from a back-end source. This approach makes a strong coupling between the View and the Model, which in my opinion is not a good practice.
A suggestion, for what it's worth. We use DataTables and Select2 a lot, and a consistent approach would be nice. :) |
Which is the status of this? |
+100 |
+1 |
1 similar comment
+1 |
+1 But can anyone tell me if there is something wrong with @renandecarlo 's solution? Seems to work quite well. |
@mktcode There's nothing wrong with it as long as you're using only html |
@Zxurian that doesn't seem so difficult. An extension of @renandecarlo's solution:
|
@trevithj that's still staying with the traditional newItemList = [
{ itemNum: 23, itemName: 'Shoe', itemShelf: 4, itemBin: 'C' },
{ itemNum: 52, itemName: 'Boot', itemShelf: 9, itemBin: 'A' },
{ itemNum: 88, itemName: 'Laces', itemShelf 2, itemBin: 'E' }
];
// or however you build / get your updated list
// actual code to update select2 options, nothing else needed
mySelect2Object.select2('data', newItemList); |
This is a major hurdle for me. When implementing shift-click to select all elements, it takes two clicks to refresh and I cannot seem to figure out how to make it trigger instantly for the life of me!!
|
+1 function bindOtherSelect2(e) { I would love to set back the placeholder but i didnt manage to do that, hope this helps someone. |
I don't understand why this wasn't labeled as critical, because it's a pretty crucial feature. You should be able to update any options without having to destroy the select2. |
If you initialise your select2 instance with the
|
The simple jQuery plugin created from this thread: (function ($) {
$.fn.refreshDataSelect2 = function (data) {
this.select2('data', data);
// Update options
var $select = $(this[1]);
var options = data.map(function(item) {
return '<option value="' + item.id + '">' + item.text + '</option>';
});
$select.html(options.join('')).change();
};
})(jQuery); Use: var data = [{ id: 1, text: 'some value' }];
$('.js-some-field').refreshDataSelect2(data); |
Thank you, nice plugin ! 😃 I had to change your |
Something like this:
|
Per documentation found at https://select2.github.io/options.html:
With that I was able to use something to the effect of:
It replaced existing elements. Or to keep existing options from elements
|
I do like that. And if u use multiple select2. U can add below line after appending.
And final event use that. |
Cool Stuff @renandecarlo |
Hello $('#descJugador').select2('val', this.id); If you do that, the select2 refresh the value dynamically. |
@dejan9393 wins the day! If you're using a custom templateSelection and/or templateResult with Ajax data that has custom properties (such as the GitHub repository example in the docs), you can't just add an asdf, because your custom templates will be missing all of the required data! Here's a slight variation... Adds a single option to the list and selects it. (Note, this works with the AJAX adapter too.) `var items = { //First, add an option to the select. //Set the value of the control and trigger an update |
It took me a while to find this issue. Could the technique provided by @dejan9393 please be added to the documentation? I think it needs to go under Programmatic Control, "Add, select, or clear items". There's another technique for adding custom data to dynamically added options mentioned $("#my-dropdown").append(new Option(...)).select2("data")[0].customparam='abc' |
This is the real and only solution!!! great job!! |
Is there a hope Select2 will get its API act together one day? |
|
`// get your data ready
|
When initializing select2, options can be provided by using the data parameter in the constructor.
Thereafter, selections (not options) can dynamically be altered by using the data api; for example
Is there any way to dynamically change options?
The text was updated successfully, but these errors were encountered: