Keeping 2 ajax (remote data) select2 fields in sync

Hi all,

I’m stuck trying to keep 2 fields on the same form in sync.

Field “foo” exists in 2 sections on a huge form. Changing it in one place needs to update the second occurrence.

My current attempt is to

  • listen to the change event on the source field
  • get select2(‘data’) from the source field
  • reset the options of the target field
  • iterate through the data items and append a new option to the target field

This works - kinda:
Modifying the first field duplicates the changes as expected in the second field.
Where it gets funky is if I then modify the second field. when I ADD another selection, somehow existing selections get duplicated.

I checked and I don’t write to the source field - in fact when the onChange handler runs the select2(‘data’) shows the duplicated options, so they get added before i attempt to sync with the first field.

What’s really strange is when I console.log() the data of the field that was just changed I see the duplicates: With 3 selections
on item not duplicated
one item duplicated once
one item duplicated twice

I’m sure I’m missing something stupid :frowning: any thoughts? Do i need to filter the data before iterating through?

jQuery(src).on("change", function() {
        if (updatingDuplFields) {
            //console.log("blocking change call during dupe update")
            return false;
        }
        updatingDuplFields = true;
        var src = $(this);
        var selections = src.select2('data');
        var request = src.closest('.requestContainer');
        
        console.log("dupe fields",request.find('.field select[fieldid='+fID+']').not(src));
        
        request.find('.field select.[fieldid='+fID+']').not(src).each( (i,o) => {
            var trg =jQuery(o);
            trg.val(null);
            selections.forEach((sel)=>{
                var newOption = new Option(sel.text, sel.id, true, true);
                trg.append(newOption);
                console.log("append to trg ",newOption);
            });
            trg.trigger('change');
        });
        updatingDuplFields = false;
    });                
});

Solved:

There is a bug in select2 that causes duplicate select objects to get added.
To exercise it, sync two fields, then alternatingly add a tag in one then the other. (AJAX remote data driven list)

I’m not enough of a dev to fix the code code, so I simply de-duplicate the .select2(‘data’), and re-set the list of selections on both source and target field.

I alternatingly add a selection up to 10 selections.
The select2 data object contains 40 duplicates…

image