Arie Sastra Arie Sastra - 1 year ago 139
jQuery Question

Set Selected Value from array using select2 javascript

I have array in javascript like this

var array = ["Impression", "Clicks", "CTR", "CVR", "CPC", "CPM", "CPA"]

I want to set selected text in select2 from one of my array but getting confused.


<option selected="selected">text</option>

this is my select2 javascript code

placeholder: "Impression",
allowClear: false,
data : array,
initSelection: true

I'm using
placeholder :"impression"
but that not selected, it just label in my select option.

Answer Source

If you want have some option to be selected from array, your html should contain that option.

For example- if you want to set "Impression" to be selected, change your html to following-

  <option selected="selected">Impression</option>

And if you want to provide your options with some value, you should change your Array to be an array of objects. For more details, please check this link.