Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Selectize automatic sorting

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.

like image 689
eliashdezr Avatar asked Dec 10 '13 23:12

eliashdezr


2 Answers

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.

like image 82
mrt Avatar answered Nov 07 '22 05:11

mrt


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.

like image 9
SpaceDog Avatar answered Nov 07 '22 05:11

SpaceDog