How to set Default Value in tagging in select2 jquery
Asked Answered
L

3

8

I am using select2 (http://ivaynberg.github.io/select2/) for my tagging input. from the example in using select2 tagging the code is look like this.

 $("#e12").select2({tags:["red", "green", "blue"]});

now my problem is how can I insert default value in my input just like in the page example in http://ivaynberg.github.io/select2/ at Tagging Support, the input has a default value of 'brown', 'red', & 'green'.

Lunseth answered 7/6, 2013 at 23:56 Comment(0)
D
19

You can initialize the Select2 control by providing a value for the hidden input:

<input type="hidden" id="e12" value="brown,red,green" />

And you can set the value of the Select2 control by passing an array to the 'val' method:

$('#tagSelect').select2('val', ['brown','red','green']);

jsfiddle demo

Dawkins answered 8/6, 2013 at 1:50 Comment(2)
@Fortis - Thanks for the notice. I fixed the external resource inks in the fiddle so it works again.Dawkins
yeah sorry i really should have done that myself but busy doing something else so I just said Id give you a heads up.Fortis
P
9

Updated version

Say you initialized your select like this:

$('.mySelect').select2({
  multiple: true,
  tags: "true"
});

Then use this 2 functions for triggering the change. (as seen in the official documentation)

$('.mySelect').val(['value1', 'value2']);
$('.mySelect').trigger('change.select2');

Where "value1" and "value2" are IDs of the option elements of the select.

Predial answered 3/3, 2017 at 10:30 Comment(0)
B
8

For Select2 4.0 I had to add the data attribute to select2 and also set value and trigger change, like this:

$('#mySelect').select2({
  data: ['one','two'],
  tags: true
});
$('#mySelect').val(['one','two']).trigger('change')
Breann answered 3/11, 2018 at 16:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.