我们正在使用由Jörn Zaefferer编写的autocomplete jQuery插件,并尝试验证是否输入了有效的选项。
这个插件有result()事件,它会在做出选择时触发。这是可以的,但当用户单击时,我也需要检查文本框中的值。因此,我们尝试了.change()和.blur()事件,但它们都提出了一个问题:当您单击results div ( 'suggest‘列表)中的条目时,.change()和.blur()事件会触发,而这是在插件将值写入文本框之前,所以此时没有什么需要验证的。
有没有人可以帮我配置事件,这样每当有人单击离开时,但不是在结果框中,我就可以检查框中的有效值。如果这是错误的方法,请告诉我正确的方法。我们最初使用这个插件是因为它的'mustMatch‘选项。这个选项似乎不是在所有情况下都有效。很多时候,一个有效的条目会被写入到文本框中,然后被插件清除为无效,我无法确定原因。
基本代码示例:
<html>
<head>
<title>Choose Favorite</title>
<script language="JavaScript" src="jquery-1.3.2.min.js" ></script>
<script language="JavaScript" src="jquery.autocomplete.min.js" ></script>
<script>
$(".suggest").autocomplete("fetchNames.asp", {
matchContains:false,
minChars:1,
autoFill:false,
mustMatch:false,
cacheLength:20,
max:20
});
$(".suggest").result(function(event, data, formatted) {
var u = this;
// Check value here
});
/* OR */
$(".suggest").change(function(me) {
//check value here
});
</script>
</head>
<body>
<label for="tbxName">Select name (I show 10):</label><br />
<INPUT type="text" id="tbxName" name="tbxName" class="suggest"><br />
</body>
</html>
发布于 2009-10-15 23:55:58
我认为,与其编写自己的函数来验证数据是否匹配,不如直接调用search()
。如果使用空的data
参数调用result()
,那么您就知道没有使用自动完成功能,并且通过在data
上调用search()
,您可以保证至少调用一次result()
。
我已经为a similar question发布了这段代码,它在这里可能也会有帮助。
autocompleteField.result(function(event, data, formatted) {
if (data) {
//auto-complete matched
//NB: this might get called twice, but that's okay
}
else {
//must have been triggered by search() below
//there was no match
}
});
autocompleteField.blur(function(){
autocompleteField.search(); //trigger result() on blur, even if autocomplete wasn't used
});
发布于 2009-04-28 08:29:53
更新:这应该可以工作。我将名称列表加载到一个名为ListOfNames的数组中,它在onBlur()事件中用来验证输入的名称是否与数据一致。你可能需要做一些调整,但我认为它应该能做你想要的。
var listOfNames = [];
$(document).ready(function(){
$.get("fetchNames.asp", function(data){
listOfNames = data.split("\r\n");
});
$(".suggest").autocomplete("fetchNames.asp", {
matchContains:false,
minChars:1,
autoFill:false,
mustMatch:false,
cacheLength:20,
max:20
});
$("#tbxName").blur(function(){
if(!listOfNames.containsCaseInsensitive(this.value)){
alert("Invalid name entered");
}
});
});
Array.prototype.containsCaseInsensitive = function(obj) {
var i = this.length;
while (i--) {
if (this[i].toUpperCase() === obj.toUpperCase()) {
return true;
}
}
return false;
}
发布于 2016-04-11 18:07:51
这是我过去用过的代码。非常干净和简单。
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$( "#currentSelectedLevel" ).autocomplete({
source: availableTags,
change: function( event, ui ) {
val = $(this).val();
exists = $.inArray(val,availableTags);
if (exists<0) {
$(this).val("");
return false;
}
}
});
https://stackoverflow.com/questions/797969
复制相似问题