You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Select2搜索输入时选中项文本异常变更问题求助(Yii2 Bootstrap5环境)

解决Yii2 Bootstrap5环境下Select2 4.x的搜索异常问题

问题定位

你遇到的是Select2 4.x版本的默认行为变更:搜索时选中项会被替换为输入内容,且默认匹配逻辑可能将选中项从下拉列表中移除,再加上Bootstrap5的样式冲突引发视觉遮挡。

具体解决方案

1. 强制保留选中项的原始文本

通过templateSelection配置,忽略搜索输入,始终显示选中选项的原始文本:

$('#your-select-id').select2({
    templateSelection: function (selected) {
        // 直接返回选中项的原始文本,不随搜索输入改变
        return selected.text || selected.id;
    },
    dropdownParent: $('#your-form-container-id') // 适配Bootstrap5容器,避免样式冲突
});

在Yii2 ActiveForm中可这样配置:

<?= $form->field($model, 'your_attribute')->widget(Select2::class, [
    'data' => ['kabupaten' => 'KABUPATEN MOJOKERTO', 'kota' => 'KOTA MOJOKERTO'],
    'options' => ['placeholder' => 'Pilih wilayah...'],
    'pluginOptions' => [
        'templateSelection' => new \yii\web\JsExpression('function(selected) { return selected.text || selected.id; }'),
        'dropdownParent' => new \yii\web\JsExpression('$("#your-form-id")'),
    ],
]) ?>

2. 让选中项始终显示在下拉列表中

修改matcher函数,强制包含已选中的选项,即使搜索词不完全匹配:

$('#your-select-id').select2({
    matcher: function(params, data) {
        // 无搜索词时返回所有选项
        if ($.trim(params.term) === '') {
            return data;
        }
        // 匹配搜索词,或是已选中项则保留
        var term = params.term.toLowerCase();
        if (data.text.toLowerCase().includes(term) || data.id === $(this).val()) {
            return data;
        }
        return null;
    }
});

Yii2中的对应配置:

'pluginOptions' => [
    'matcher' => new \yii\web\JsExpression('function(params, data) {
        if ($.trim(params.term) === "") {
            return data;
        }
        var term = params.term.toLowerCase();
        if (data.text.toLowerCase().includes(term) || data.id === $(this).val()) {
            return data;
        }
        return null;
    }'),
],

3. 修复样式遮挡问题

添加自定义CSS,确保下拉列表的选中项不会遮挡其他选项:

.select2-results__option--selected {
    position: relative;
    z-index: 1;
    margin-bottom: 4px;
    background-color: #e9ecef !important; /* 匹配Bootstrap5选中样式 */
}

验证效果

配置完成后,输入“Moj”时:

  • 选中项文本会保持原始的“KABUPATEN MOJOKERTO”或“KOTA MOJOKERTO”
  • 两个选项都会正常显示在下拉列表中,不会被遮挡或隐藏

内容的提问来源于stack exchange,提问作者fammi farendra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 20:44:54