0
votes

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>
1
If you included the HTML and a small bit of JS so we could better understand the environment you have that would be useful.Kevin Brown-Silva
added html and javascript.. i'm using this jquery for select box select2.github.ioTorostar
Take it a step further and create it @ jsfiddle.netvol7ron

1 Answers

1
votes

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