Choices-js / Choices

A vanilla JS customisable select box/text input plugin ⚡️
https://choices-js.github.io/Choices/
MIT License
6.13k stars 605 forks source link

Display selected choices in original order #845

Open onecreative opened 4 years ago

onecreative commented 4 years ago

By default, the selected choices are displayed in the field in the order they were selected. However, I would like them to always show in their hard-coded order.

Basically, Choices.js provides the shouldSort option to determine if the list of choices shows in its original order or in alphabetical order. But I would like the selected choices to have the same kind of option.

Is this possible already? If not, is it something we could see in a feature release?

sabat24 commented 4 years ago

I needed this also and made some workaround.

Add a data attribute to your select for example <select data-sortingorder="[2,1]"> where values are IDs ordered just like you have saved it to DB for example.

Then make use of sorter callback

new Choices($element[0], {
            shouldSortItems: false,
            sorter: function (a, b) {
                let selectingOrder = $element.data('sortingorder') || [];
                let aOrder = selectingOrder.indexOf(a.value*1);
                let bOrder = selectingOrder.indexOf(b.value*1);
                return bOrder < aOrder;
            },
        });

It will keep your sorting order for selected elements, but... If you use removeItemButton option, when you remove preselected options they will appear on your list as first options. Because it's basically changes sorting order of the list itself.

For me it's ok so I didn't change that behaviour. However if you want to modify code itself, it should be easy to create another callback to sort only preselected items on initialization without touching the list itself.

I made use of jQuery here for selecting objects, but it doesn't matter.

Xon commented 1 month ago

I plan to implement a shouldSortItemsByChoices option for v11.0.0 as it ended up being something I will also need.