Tobias
Tobias

Reputation: 964

Dynamically edit option in select2

I have a multiselect widget which I'm using select2 for. I load the options through AJAX and it is all working fine.

However, I added a clickable 'edit' icon to the options as they appear in the field of selected items, right next to the 'delete' icon. I have hooked this up to a modal form which edits the items through AJAX. After the edit is successful I obviously want to update the selected option in the select2 field to match this.

Is there a way to edit the selected options in this way with select2?

I have tried editing the tag and executing .trigger('change') on the option but it didn't do anything. I also looked at the examples of programmatic access in the select2 documentation but they seemed to be more about selecting already existing options than editing the 'text' of the options themselves.

Any help appreciated.

This is how I have set up my select2 widget:

function formatFlavorSelection(flavor) {
    var $flavor = $(
        '<span class="glyphicon glyphicon-pencil" onClick="editFlavorSelection(' + flavor.id + ', event);"></span><span>' + flavor.text + '</span>'
    );
return $flavor;

};

$(".select2-flavor").select2(
    ajax: {
        url:url,
        dataType: 'json',
        delay: 250,
        data: function (params) { 
            return { 
                q: params.term // search term
            };
        },
        processResults: function (data, page) {
            var resultData = [];
            data.forEach(function(entry) {
                resultData.push({ id: entry.id, text: entry[dataName]})
            });
            return {
                results: resultData
            };
        },
        cache: true
    },
    minimumInputLength: 0,
    templateSelection = formatFlavorSelection
);

Upvotes: 1

Views: 2178

Answers (1)

Kevin Brown-Silva
Kevin Brown-Silva

Reputation: 41671

When you select a result in Select2, an <option> tag is automatically created where the value attribute is equivalent to the id of the data object that was selected. You can edit this <option> tag afterwards and trigger a change event on the original select, and Select2 will try to work with the new data.

The problem comes if you Select2 has already cached the data objects onto the <option> elements, as the data objects won't be regenerated after it happens the first time (with a few small exceptions). You need to manually clear the cache, which is stored as the data key in the jQuery .data() on the <option>.

So you would call

$option.removeData('data');

Where $option is a jQuery element pointing to the <option> that you just modified. It is after this that you trigger the change event, so Select2 knows to rebuild the internal cache and detects the changes that were made.

Upvotes: 1

Related Questions