在 Yii2 中,我希望当用户开始输入时,我的多选字段之一能够自动完成。我已经加载了所有产品,但是它们超过了1000个,而且加载速度非常非常慢。因此,我需要一个下拉列表,它允许我在建议我选择选项列表之前输入一些产品标题。
<?php
$cats = Product::find()->where('active = 1')->all();
$prArr = array();
if ($cats) {
foreach ($cats as $cat) {
$prArr[$cat->id] = $cat->title;
}
}
$selectedProducts = '';
if (isset($_POST['RelProducts']) and ! empty($_POST['RelProducts'])) {
$selectedProducts = array();
foreach ($_POST['RelProducts'] as $cat) {
$selectedProducts[$cat] = $cat;
}
}
?>
<?= Html::dropDownList('RelProducts[]', $selectedProducts, $prArr, ['multiple' => 'multiple', 'style' => 'width:300px;', 'rows' => 10, 'id' => 'relProductSelect']); ?>
这是脚本:
$('#relProductSelect').multiSelect({
selectableHeader: "<a href='#' id='select-all-rel-prod'>Избери всички</a><br /><input type='text' class='search-input' autocomplete='off' placeholder='търси...' style=\"width:100%;margin-bottom:5px;\">",
selectionHeader: "<a href='#' id='deselect-all-rel-prod'>Премахни всички</a><br /><input type='text' class='search-input' autocomplete='off' placeholder='търси...' style=\"width:100%;margin-bottom:5px;\">",
afterInit: function (ms) {
var that = this,
$selectableSearch = that.$selectableUl.prev(),
$selectionSearch = that.$selectionUl.prev(),
selectableSearchString = '#' + that.$container.attr('id') + ' .ms-elem-selectable:not(.ms-selected)',
selectionSearchString = '#' + that.$container.attr('id') + ' .ms-elem-selection.ms-selected';
that.qs1 = $selectableSearch.quicksearch(selectableSearchString)
.on('keydown', function (e) {
if (e.which === 40) {
that.$selectableUl.focus();
return false;
}
});
that.qs2 = $selectionSearch.quicksearch(selectionSearchString)
.on('keydown', function (e) {
if (e.which == 40) {
that.$selectionUl.focus();
return false;
}
});
},
afterSelect: function () {
this.qs1.cache();
this.qs2.cache();
},
afterDeselect: function () {
this.qs1.cache();
this.qs2.cache();
}
});
如何加快请求?
最佳答案
那么,需要最少努力的解决方案之一可能是使用该选项
minimumInputLength
: Minimum number of characters required to start a search.
只有当搜索词达到一定长度时才开始过滤结果,效率更高。就您而言,它可以创造差异。
根据您的评论,您正在使用 KartikSelect2-multiselect
但你还没有添加它的源代码,而是js代码用于jquery多选,但我将为你提供服务器端实现的代码
Select2::widget([
'name' => 'my-dropdown',
'data' => $data,
'options' => ['placeholder' => 'Select a product ...', 'multiple' => true],
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength':3
],
])
您可以根据您的要求调整输入值。 希望对您有所帮助。
关于javascript - yii2 中的 dropDownList 自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48826843/