我最近把我的一些自动完成插件从bassistance生产的转移到了jQuery UI自动完成。
如何使用回调和其他选项实现“mustMatch”和“selectFirst”,而不修改核心自动完成代码本身?
我最近把我的一些自动完成插件从bassistance生产的转移到了jQuery UI自动完成。
如何使用回调和其他选项实现“mustMatch”和“selectFirst”,而不修改核心自动完成代码本身?
我认为我解决了这两个特性...
为了使事情变得更容易,我使用了一个常见的自定义选择器:
$.expr[':'].textEquals = function (a, i, m) {
return $(a).text().match("^" + m[3] + "$");
};
代码的其余部分:
$(function () {
$("#tags").autocomplete({
source: '/get_my_data/',
change: function (event, ui) {
//if the value of the textbox does not match a suggestion, clear its value
if ($(".ui-autocomplete li:textEquals('" + $(this).val() + "')").size() == 0) {
$(this).val('');
}
}
}).live('keydown', function (e) {
var keyCode = e.keyCode || e.which;
//if TAB or RETURN is pressed and the text in the textbox does not match a suggestion, set the value of the textbox to the text of the first suggestion
if((keyCode == 9 || keyCode == 13) && ($(".ui-autocomplete li:textEquals('" + $(this).val() + "')").size() == 0)) {
$(this).val($(".ui-autocomplete li:visible:first").text());
}
});
});
如果你的自动完成建议中包含正则表达式使用的任何“特殊”字符,那么你必须在自定义选择器中对m[3]中的这些字符进行转义:function escape_regexp(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
并更改自定义选择器:
$.expr[':'].textEquals = function (a, i, m) {
return $(a).text().match("^" + escape_regexp(m[3]) + "$");
};
我使用了这么简单的代码作为mustMatch,它运行良好。希望对别人有所帮助。
change: function (event, ui) {
if (!ui.item) {
$(this).val('');
}
}
autoFocus: true
。 - Elliott我认为我用这段代码实现了mustMatch功能...不过需要进行彻底的测试:
<script type="text/javascript">
$(function() {
$("#my_input_id").autocomplete({
source: '/get_my_data/',
minChars: 3,
change: function(event, ui) {
// provide must match checking if what is in the input
// is in the list of results. HACK!
var source = $(this).val();
var found = $('.ui-autocomplete li').text().search(source);
console.debug('found:' + found);
if(found < 0) {
$(this).val('');
}
}
});
});
</script>
change: function (event, ui) {
if (options.mustMatch) {
var found = $('.ui-autocomplete li').text().search($(this).val());
if (found < 0) {
$(this).addClass('ui-autocomplete-nomatch').val('');
$(this).delay(1500).removeClass('ui-autocomplete-nomatch', 500);
}
}
}
.ui-autocomplete-nomatch { background: white url('../Images/AutocompleteError.gif') right center no-repeat; }
$('form').submit(function() {
if ($(".ui-autocomplete li:textEquals('" + $(this).val() + "')").size() == 0) {
$(this).val('');
$("span").text("Select a valid city").show();
return false;
}
});
这将防止表单被提交并显示一条消息。
change: function(e, ui) {
if (!ui.item) {
$(this).val("");
}
}
这段代码与bassistance的原始功能类似,可以处理在自动完成时没有匹配项的情况:
response: function(e, ui) {
if (ui.content.length == 0) {
$(this).val("");
}
}
这适用于静态数组源或JSON数据源。与 autoFocus: true
选项结合使用,似乎以高效的方式完成所有需要的操作。
您可能想处理的最后一种情况是,当在文本框中键入无效值并按下 ESCAPE 键时该怎么办。我的做法是使用第一个匹配结果的值。以下是我如何实现...
首先,在自动完成插件之外声明一个变量来保存最佳匹配结果。
var bestMatch = "";
open: function(e, ui) {
bestMatch = "";
var acData = $(this).data('uiAutocomplete');
acData.menu.element.find("A").each(function () {
var me = $(this);
if (me.parent().index() == 0) {
bestMatch = me.text();
}
});
}
.on("keydown", function(e) {
if (e.keyCode == 27) // ESCAPE key
{
$(this).val(bestMatch);
}
})
bestMatch
变量(如果选择清空字段,则根本不需要该变量)。我用来实现“mustMatch”的解决方案:
<script type="text/javascript">
...
$('#recipient_name').autocomplete({
source: friends,
change: function (event, ui) {
if ($('#message_recipient_id').attr('rel') != $(this).val()) {
$(this).val('');
$('#message_recipient_id').val('');
$('#message_recipient_id').attr('rel', '');
}
},
select: function(event, ui) {
$('#message_recipient_id').val(ui.item.user_id);
$('#message_recipient_id').attr('rel', ui.item.label);
}
});
...
</script>
CSS(.hjq-combobox是一个包装span)
.hjq-combobox .ui-button { margin-left: -1px; } .hjq-combobox .ui-button-icon-only .ui-button-text { padding: 0; } .hjq-combobox button.ui-button-icon-only { width: 20px; } .hjq-combobox .ui-autocomplete-input { margin-right: 0; } .hjq-combobox {white-space: nowrap;}
注意:此代码正在https://github.com/tablatom/hobo/blob/master/hobo_jquery_ui/vendor/assets/javascripts/combobox.js更新和维护。
回复晚了,但希望对某人有所帮助!
考虑自动完成小部件中的两个事件:
1)更改 - 当字段模糊和值更改时触发。
2)响应 - 在搜索完成并显示菜单时触发。
按如下方式修改更改和响应事件:
change : function(event,ui)
{
if(!ui.item){
$("selector").val("");
}
},
response : function(event,ui){
if(ui.content.length==0){
$("selector").val("");
}
}
<script type='text/javascript'>
function init_autocomplete( args )
{
var resultCache = {};
var currentRequestTerm = null;
var closeCallback = function()
{
// Clear text field if current request has no results
if( resultCache[currentRequestTerm].length == 0 )
$(args.selector).val('');
};
var sourceCallback = function( request, responseCallback )
{
// Save request term
currentRequestTerm = request.term;
// Check for cache hit
// ...
// If no cache hit, fetch remote data
$.post(
dataSourceUrl,
{ ... }, // post data
function( response )
{
// Store cache
resultCache[request.term] = response;
responseCallback( response );
}
};
$(args.selector).autocomplete({
close: closeCallback,
source: sourceCallback
});
}
</script>