gpt4 book ai didi

jquery-select2 - 如果只有 1 个选项可用,则 Select2 下拉自动选择

转载 作者:行者123 更新时间:2023-12-01 15:52:33 25 4
gpt4 key购买 nike

我有一个使用远程数据源的 select2 下拉框。

我想做的是如果/当搜索只返回一个选项时,自动选择它。即,用户不必单击选项进行选择。

$("#searchInfo_Entity_Key").select2({
ajax: {
url: "/Adjustment/GetEntity",
dataType: 'json',
delay: 250,
data: function (params) {
return {
term: params.term, // search term
};
},
processResults: function (data) {
return {
results: data
};
},
results: function (data) {
return { results: data };
},
},
initSelection: function (element, callback) {
var data = [];
callback(data);
},
minimumInputLength: 2,
allowClear: true,
placeholder: "Select an entity"

});

最佳答案

这是一个自定义匹配器,它环绕默认匹配器并计算有多少匹配。如果只有一个匹配项,那么它将选择该匹配项,更改它,然后关闭下拉框。

(未使用远程数据进行测试。)

$(function() {

var matchCount = 0; // Track how many matches there are
var matched; // Track the ID of the last match

$('select').select2({
placeholder: 'Product Search',
allowClear: true,
matcher: function(params, data) {
// Wrap the default matcher that we have just overridden.
var match = $.fn.select2.defaults.defaults.matcher(params, data);

// If this is the first option that we are testing against,
// reset the matchCount to zero.
var first = $(data.element).closest('select').find('option').first().val();
if (first == data.id) matchCount = 0;

// If there was a match against this option, record it
if (match) {
matchCount = matchCount + 1;
matched = data.id;
}

// If this is the last option that we are testing against,
// now is a good time to check how many matches we had.
var last = $(data.element).closest('select').find('option').last().val();
if (last == data.id && matchCount == 1) {

// There was only one match, change the value to the
// matched option and close the dropdown box.
$(data.element).closest('select')
.val(matched).trigger('change')
.select2('close');
return null;
}

// Return the default match as normal. Null if no match.
return match;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.full.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>

<select style="width: 20em">
<option value=""></option>
<option value="100">Product One</option>
<option value="200">Product Two</option>
<option value="300">Product Three</option>
<option value="400">Product Four</option>
<option value="500">Product Five</option>
</select>

关于jquery-select2 - 如果只有 1 个选项可用,则 Select2 下拉自动选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29980182/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com