简体   繁体   中英

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. It is triggered by radiobutton click. Select2 contains income and expense categories. 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. Please help. Thank you.

This is worked for me-

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

'#accessories' is the id of select2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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