Arie Sastra Arie Sastra - 6 months ago 68
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.

In
<HTML>
is

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


this is my select2 javascript code

$('.params_1').select2(
{
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

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-

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

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.

Comments