0

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>
welworx
  • 370
  • 2
  • 14
  • 2
    Please show what you tried. We can't help you get it to work if we don't see what you did wrong. – Barmar Apr 13 '15 at 20:20
  • are you trying something like this http://stackoverflow.com/questions/19639951/how-do-i-change-selected-value-of-select2-dropdown-with-jqgrid ? – Dhiraj Apr 14 '15 at 04:59

1 Answers1

0

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).

Kevin Brown-Silva
  • 40,873
  • 40
  • 203
  • 237
  • thanks for your answer. Even after i have added this, it didn't work in the beginning. After a while i figured out that I had a second jquery version loaded (through an other plugin) .. I can't remember exactly what i did, but after cleaning the js code and removing other plugins it worked. :D – welworx Apr 27 '15 at 05:06