Search code examples
jqueryjquery-select2jquery-select2-4

How to use local json array and infinite scroll together in Select2 4.0?


Since it's expensive to create/remove a lot of <option> tags on the DOM, I'm looking for a way to use large local JSON along with infinite scroll in Select2 4.0. I also want to be able to properly get/set/update values. There is this stackoverflow question (of which I provided a muddy solution) but my solution has 2 problems:

  1. I can clear out unselected options in the single source select and the Select2 control will not break. This keeps unneeded options from building up in the source select (since I'm using a local JSON array for data). However, if I try to do the same for multiple selects this will break functionality in Select2. See this section in the jsFiddle example:

    if(!this.$element.prop('multiple')){
        findValue = [findValue];
        this.$element.html();     // <-- if I do this for multiple then it breaks
    }
    
  2. This overall solution is convoluted. Is there a better way to accomplish having large local JSON and infinite scroll in Select2 (with ability to get/set/update values as shown in the fiddle below)?

Here's my full jsFiddle here.


Solution

  • Ok, diving deeper into the source I concluded that what I'm trying to do is to reverse the role that Select2 takes in it's default selectAdapter methods. I want my json array to be the authority, not the source select:

    1. There are 2 other important methods I can decorate: select and unselect.
    2. Since I am manipulating an array beyond initialization, then I need to set/update data using other means. If I were to set the data directly on the source select, this wouldn't make sense because the source select doesn't know or have all the options (the array holds them, and returns paginated result set of options).
    3. I can use jQuery's data storage on the source select to set the value, then trigger a change and let Select2's decorated methods grab that value and check to see if it exists. If it exists, then we'll add it to the source element. We can also clear any other options on the source select since all we need is the selected option (so we can do .val() on the source select and also forms can submit the value too). This should create a cleaner and much more cohesive code!

    New jsFiddle here works.