Select2 with multiple options, defer the loading

I am building a website where the list of objects are to be filtered in many different ways (for some properties, multiple selections is allowed; others have dependent selections, so when changing the value of a property, limits the available properties shown for another property). In PHP I have completed the coding and it works as expected.

For example of what I have. Some properties should list all values for that property in the database (high level properties), while other properties should only list the values that are available within the currently filtered collection of objects (since those are relevant to continue filtering).

To make the selection boxes a bit more appealing and easy to use (not having to Ctrl+Click to select extra values and deselect), I decided to use Select2 library.

Based on the advice from various other sources, I am using the following JS, pushed to the stack on the component:

var select2_options = {};
$(document).ready(function() {
  $('.select2field').select2(select2_options).on('change', function(e){
    @this.set($(this).data('model'), e.target.value);
  });
});
document.addEventListener("livewire:load", function (event) {
  Livewire.hook('message.processed', function (message, component){
    $('.select2field').select2(select2_options);
  });
});

The top section creates the Select2 Fields (since there are many, I am using a class of “select2field” on all of them, and have a data-attribute “data-model”, which defines which model this field belongs to).

The bottom section re-initialize the select2 after Livewire completed the round trips.

The part I am having trouble with, due to the dynamic nature of some of my select fields, making a selection can remove all other options for that select field, even though multiple selections are supported. I want to defer the update roundtrip for these until the person made their full selection, and click on a button to filter.

How do I defer the livewire roundtrip when setting the model value programmatically?

I am doing in almost the same way as you, except you might avoid double initializations using following script:

    function initSelect2()
        {
            // add select2 initialization per element
            $('.select2:not(.select2-enabled)').each(function(i, obj) {
                $(obj).addClass('select2-enabled');
                select2init(obj);
            });
        }

And the function select2init() does actual init of select2 using some element attributes as initialization parameters.

And regarding selected options I am rendering them as HTML sub elements with attribute selected.