简体   繁体   中英

select2 change event without removing already selected options

I'm using select2 with multiple options and programmatic access to select also with a button. It works fine but when I click on the button all previously selected values are removed and only the value from the clicked button gets selected. Since I'm using multiple select it would make sense to add the clicked value and leave the previously selected without removing them... Is there another event to trigger besides "change" that does not remove values but adds them instead?

<select id="id_entities" class="js-example-programmatic" style="width:100%" multiple="multiple">
</select>

<td><button id="prefix_{{teu.entity_id}}" class="js-programmatic-set-val" value="{{teu.entity_id}}" name="{{teu.entity}}"><i class="fa fa-plus"></i></button></td>
<td>{{teu.entity}}</td>
<td>{{teu.user}}</td>

<script >
$(".js-example-programmatic").select2({
    minimumInputLength: 2,
    placeholder: "Select entities...",
    allowClear: true,
    multiple:true,
    delay: 250,
    tags:false,
    ajax: {
        url: '/entities/search/autocomplete/',
        dataType: 'json',
        data: function (parms, page) { return { title: parms.term }; },
    },
});
</script>
<script>
var $example = $('#id_entities');
$("button[id^='prefix_']").click(function(){
   value = $(this).attr('value');
   value_name = $(this).attr('name')
 if ($('#id_entities option[value="'+value+'"]').length > 0) {
 } 
  else { 
     $("#id_entities").append('<option value="'+value+'">'+value_name+'</option>');
  }
$example.val(value).trigger("change");
  });
</script>

well, without seeing a working demo, I assume what you want is to append tags on to a select2 without erasing what tags/multi-selects are already there? If so, you would need to evaluate the element value, and append new vals rather than just calling $example.val(value), which replaces the value of said element

var data = $(test).select2('data');
data.push({id:5,text:"fixed"});
$(test).select2("data", data, true); // true means that select2 should be refreshed

Seels like a duplicate of SELECT2 -> Add data without replacing content

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM