Select2 issue with multiple values

1.1k views Asked by At

I have a webpage that requires to use select2 component. It is required to show selected values on load as well. In my JS file I have two constructs

JS - Construct 1 for choose/remove options

    $("#inp_select_linkproject").select2({
      minimumInputLength: 2,
      maximumSelectionLength: 1,
    ajax: {
          type  : 'POST',
          url: '../../ase.php',
        dataType: 'json',
        delay: 250,
        data: function (term, page) {
          return {
              wildcardsearch: term, // search term
              data_limit: 10,
              data_offset: 0,
              page_mode:"SELECT",
              agent_id:$("#ipn_hdn_userid").val()
          };
        },
        processResults: function (data, page) {
            return { results: data.dataset};
        },
        cache: true
      },
      escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
});

JS - Construct 2 for catering onload

    $.fn.getCurrentSelect2data = function(){
    $("#inp_select_linkproject").val(null).trigger("change");
    var $element = $('inp_select_linkproject').select2(); // the select element you are working with
     var postFormData =  {
             'eucprid'          : $("#ipn_hdn_eucprid").val()
        };
    var $request = $.ajax({
          type  : 'POST',
          url: '../../ase_x.php',
          data  : postFormData,
        dataType: 'json'
      });

    $request.then(function (data) {
      // This assumes that the data comes back as an array of data objects
      // The idea is that you are using the same callback as the old `initSelection`
        console.log("rowselect,data0-"+data[0].text);
        for (i=0; i<data.length; i++) {
            $('#inp_select_linkproject').append($("<option/>", {
                value: data[i].id,
                text: data[i].text,
                selected: true
            }));
        }
        $('#inp_select_linkproject').trigger('change');
    });
}

Now the issue is that repetition of selection is happening and the number of repetition increases on choosing more options. Could you please help me out here? enter image description here

1

There are 1 answers

0
Kevin Brown-Silva On BEST ANSWER

The issue you are hitting is not specific to Select2, if you remove the calls to Select2 from your code you will see it happens to a standard <select> as well. The problem is that you are not clearing out old selections before you register the new selections, so they are just getting appended to the end (and causing duplicates).

You can fix this by calling

$select.empty();

Right before you start appending new options to your $select. In your case, that would mean changing your callback to

// clear out existing selections
$('#inp_select_linkproject').empty();

// add the selected options
for (i=0; i<data.length; i++) {
    $('#inp_select_linkproject').append($("<option/>", {
        value: data[i].id,
        text: data[i].text,
        selected: true
    }));
}

// tell select2 to update the visible selections
$('#inp_select_linkproject').trigger('change');