4

I am trying to set default value of select2 single select dropdown : http://ivaynberg.github.io/select2/.

I have the select2 dropdown working. But i am not sure how to set the default value. For example, say the list of values is - test1, test2, test3. How do i set 'test1' as the default value of the single select drop down.

$(function(){
var testData = [{id:0, text:"test1"}, {id:1, text:"test2"}, {id:2, text:"test3"}];

$('#select2customdata').select2({placeholder:"Search Stuff",  data: {results: testData, text:'text'}});

$('#select2customdata').select2().select2("val", "test1");
 });

And html has :

<input type="hidden" id="select2customdata" style="width:300px"> </input>

As you can see, i am using the select2("val", "some-val") to set a default value. It does not work for me.

EDIT: I figured out the solution, if val is used, have to have initselection in the options. Other solution is to use :

$('#select2customdata').select2("data", {"id": id_val, "text": text_val})
doubleo
  • 4,389
  • 4
  • 16
  • 19

1 Answers1

5

based on document val:

Gets or sets the selection. If the value parameter is not specified, the id attribute of the currently selected element is returned. If the value parameter is specified it will become the current selection.

But pay attention to this notice from doc:

Notice that in order to use this method you must define the initSelection function in the options so Select2 knows how to transform the id of the object you pass in val() to the full object it needs to render selection. If you are attaching to a select element this function is already provided for you.

take a look at this post.

Community
  • 1
  • 1
Hasan Ramezani
  • 5,004
  • 24
  • 30