Prevent Selectize automatic sorting
Asked Answered
T

2

15

I have an array of objects that is provided from a WebService (the order of the list is important). I loaded the JSON object into a Selectize control but it re-orders the list without using the order of the object.

This is the link of the current problem.

$('#testSelect').selectize({
    maxItems: 1,
    valueField: 'Id',
    labelField: 'Descripcion',
    searchField: 'Descripcion',
    options: data
});

Fiddle here: http://jsfiddle.net/LYYab/

I have disabled the 'sortField' but it doesn't work.

Any help would be greatly appreciated.

Thanks.

Tweeddale answered 10/12, 2013 at 23:17 Comment(4)
I assume you mean the default order when you first get the drop down? Rather than once you've entered something in the box? Once you've edited something it's going to sort the 'best' matches. Sadly I'm not actually sure it's possible to do that because it's not what Selectize is for.Impressure
I mean that the dropwdown shoul be something like this: - Todos - Armtas - Comtrek - Earthwax - Flotonic That's the order of the JSON Object.Tweeddale
UPDATE: One simple solution to this case: Add a whitespace before the Word I want to be on the Top.Tweeddale
Is there no systemtic and simple way to disable sorting in this widget? It's ridiculous...the workarounds are all hacks...Chiasma
D
14

Your sortField could look like this:

sortField: [{field: 'Descripcion', direction: 'desc'}, {field: '$score'}]

Make sure the overriden sortField contains the special $score field. Otherwise, as per documentation, it will be added in front of all the other fields effectively overriding the provided order.

Degeneration answered 31/5, 2015 at 23:6 Comment(1)
Cheers @Degeneration make my day this snippet !Skip
I
9

For some reason I assumed you didn't have access to the data before it was passed to Selectize. If you do you can just add an sort index:

var currentSortId = 0;    
$.each(data, function(i, v) { 
    currentSortId = currentSortId + 1; // First ID is 1!
    v.sId = currentSortId;
});

and then reference that in the Selectize options with sortField: 'sId'.

Fiddle here

Of course that only works until someone types in the text box, then the order is based on what's the 'best match' for the texted typed. If you must preserve the order when someone is typing you'll need to define your own score function -- you'll need a function that returns a function. The inner function takes and item and the current query and needs to return the sId to preserve the order if the item matches, otherwise return 0.

See score under callbacks in the documentation.

Impressure answered 12/12, 2013 at 9:59 Comment(1)
For some reason the default sorting of selectize, which is supposed to be alphabetical, randomly put some items of top that didn't correspond with the alphabetical order one would expect. This solved the issue for me.Schulze

© 2022 - 2024 — McMap. All rights reserved.