1

"Select2" means: http://ivaynberg.github.io/select2/

Now, my question is: I have hard coded source for the select2 widget, for example:

<select>
    <option value = "1">A</option>
    <option value = "2">B</option>
    <option value = "3">C</option>
</select>

Then, when I choose A and B two options, and use:

var result = $("#id").select2("val"); 

I can get the result is equal to A,B. So next when I want to reload the result:

$("#id").select2("val", result);

it can not succeed, because the widget cannot separate they are two different options.

How can I solve that problem, cannot use split(",") command, because maybe some options have a comma.

qiweiren
  • 103
  • 11
  • Another discussion about it http://stackoverflow.com/questions/12889552/how-to-set-selected-value-in-multi-value-select-in-jquery-select2 – ProgrammerV5 Feb 06 '14 at 20:57
  • Actually, my problem is not the same with that one, he uses an array to store the selected value, while my question is: When I got the selected value as a string, for example: "1,2", then how can I store the string to an array? just like array[0] = 1, array[1] = 2, cannot use the split(","). – qiweiren Feb 06 '14 at 21:21

1 Answers1

0

Ok, let's do something, I just created a sample on fiddle and we can work on it so you can do what you need.

So far this is what I can, you can select multiple items on the top select2 then press a button, get the selected items and then select the exact same items on a different select2 (the values contain commas in it). This is pretty much what you want to do (save and restore).

The fiddle is at http://jsfiddle.net/5P9Zc/

$(".mimicValues").click(function() {
    var test = $(".origin").val();
    // Save the values into TEST
    $(".origin").val().forEach(function(entry) {
    console.log(entry);
});
   alert(test);
   // Restore the values in TEST
   $(".mimic").val(test);
});

Also, pay attention to the version of select2 you are using, there are several enhancements on the newer version of it.

ProgrammerV5
  • 1,915
  • 2
  • 12
  • 22
  • Thank you so much, that's also what I chosed to do so. Actually I simply change not to use: `var result = $("#id").select2("val");` but use: `$("#id").val().split('||');`. Then different values can be separated not with comma. – qiweiren Feb 09 '14 at 03:50
  • Actually, because I just used the select2 version 2.1, it doesn't support to change the separator content in select2 widget. If I change it to the 3.4.5 version, it provides the separator constructor. Here is the link: http://ivaynberg.github.io/select2/index.html#documentation – qiweiren Feb 09 '14 at 03:58