简体   繁体   English

Yii2 Select2 在 select2.empty() 后不清除选定的值

[英]Yii2 Select2 doesn't clear selected value after select2.empty()

$('#category-id').empty();
for (i = 0; i < response[0].category.length; i++) {
    $('#category-id').append($('<option></option>') //here typo mistake
      .attr('value', response[0].category[i].id)
      .attr('selected', 'selected')
      .text(response[0].category[i].category_name));
}

This is from javascript code _form.php in Transaction View.这是来自事务视图中的 javascript 代码_form.php It is triggered by radiobutton click.它由单选按钮单击触发。 Select2 contains income and expense categories. Select2 包含收入和费用类别。 When I selected one income category and clicked expense radio button.当我选择一个收入类别并单击费用单选按钮时。 The option changed expense categories.该选项更改了费用类别。 But the selected income category still showed.但选择的收入类别仍然显示。 It didn't clear.没说清楚。

<?=
$form->field($model, 'category_id')->widget(Select2::classname(), [
    'data' => Category::getCategoryListByType($model->transaction_type),
    'options' => [
        'id'  => 'category-id',
        'placeholder' => Yii::t('frontend/common', 'Please select one'),
        'allowClear' => true,
    ],
    'pluginOptions' => ['allowClear' => true]
]);
?>

Select2 php code.选择2 php代码。 Please help.请帮忙。 Thank you.谢谢。

This is worked for me-这对我有用-

$('#accessories').val('').trigger("change");

'#accessories' is the id of select2 '#accessories' 是 select2 的 id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM