Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to save sorting order in select2() field?

I'm using select2() field using select2 library and Drag and Drop Sorting is enabled in the field.

It works well, but once i save it, the ordering break and they are ordered alphabetically.

I was wondering if its possible to anyhow save ordering of elements after drag drop in select2() fields.

Please suggest.

like image 549
uday.blob Avatar asked Nov 19 '25 20:11

uday.blob


1 Answers

Per Select2 documentation, the new ordered values are saved in a attached hidden field. http://ivaynberg.github.io/select2/

(right click on the Input field and then inspect element to find the line below just after the div#select2-container)

There are two options that might work for you:

Option 1:Easy one

Check the ordering of how you are feeding the control, specific on:

$("#e15").select2({tags:["red", "green", "blue", "orange", "white", "black", "purple", "cyan", "teal"]});

The control just render the same order that the above line is specified.

If you are not saving those values as comma separated text and instead as row records, maybe your database query is ordering them alphabetically.

Option 2: A little bit further

This code will serve you to save the ordered values in a cookie, so you can have the same order within your whole session.

$(function(){

  if ($.cookie('OrderedItemList') != null){
      $("#e15").select2({tags: $.cookie('OrderedItemList').split(',')});
   }

  $("#e15").on("change", function() { 
                         $("#e15_val").html($("#e15").val());
                         $.cookie('OrderedItemList', $("#e15").val(), { expires: 365 });
                           });

});

Please note, this code might not work for database bound fields, you might need to add some code if thats what you need.

like image 88
DJ. Avatar answered Nov 21 '25 08:11

DJ.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!