1
votes

Is it possible to set certain options as selected in yii2 select2 widget from jquery. The widget is not initialised through js but it is bound to model attribute in form. Any help would be appreciated

Code:

echo $form->field($model, 'news_tags')->widget(Select2::classname(), [
                    'data' => ArrayHelper::map(app\models\Topics::findAll(['status' => 1]), 'tp_id', 'title'),
                    'options' => ['multiple' => true, 'placeholder' => 'Select Tags ...'],
                    'pluginOptions' => [
                        'tags' => false,
                        'allowClear' => true
                    ],
                ])->label(FALSE);

I am trying to use an ajax call and on succes i want to add some tags from clientside.

1
Please share your code or fiddle - Mohit Tanwani
Are you using kartik select2? - Salman Riyaz
It is possible.put your codes - Zahra Jalali
Sorry for being late! I'll put the codes rightaway - Jaison Mathew
Yes! I am using kartik select2. - Jaison Mathew

1 Answers

3
votes

As is presented in docs https://select2.github.io/examples.html#programmatic you can use following code:

$("#form-field").val("5").trigger("change");

and it will select option, that has id 5