Q:

jquery-select2: selection of multiple options at once with a button

I have a list of users that can be selected (multiple selection is possible). Of course all users can be selected manually, which is excellent. 
Further on I have user groups. Most of the times it is required to select only those users of a group. Therefore i would like to have a kind of quickway to add all the users, just by clicking on the a group name.
I'm a big fan of select2, but i wasn't able to get this to work.
I have found that via the .val() function elements could be selected. But these elements are only displayed when another element is selected.
So i need a kind of update function. How can i do this?
I have tried to trigger events (like change) but without success.
Can you help me?
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0-rc.2/css/select2.css" rel="stylesheet" />
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0-rc.2/js/select2.full.js"></script>

<script type="text/javascript">
$("#id_invited_user").select2({
 "placeholder": "Select user",
});

$("#testbuttonclick").on('click',function (clickEvent){
            clickEvent.preventDefault();
             $("#id_invited_user").val([1,2]);
          });
</script>

<select multiple="multiple" class="selectmultiple form-control" 
id="id_invited_user" name="invited_user">
<option value="1">Option1</option>
<option value="2">Option2</option>
<option value="3">Option3</option>
<option value="4">Option4</option>
<option value="5">Option5</option>
</select>

<a href="" id="testbuttonclick" >select predefined options</a>

A:

You have all of the right code, except you are missing one important detail.
Whenever you change the value of Select2 (or any other JavaScript component), you should always trigger the change event.  This event is nativly triggered by the browser when the value is changed, but it must be manually triggered when the value is changed programmatically.
$("#id_invited_user").trigger("change");

This should always be placed after your call to .val(xyz).

