JQuery自动完成验证选定的值

Bre*_*ski 22 jquery autocomplete event-handling

我们正在使用的内容即自动完成的jQuery插件乔恩Zaefferer,并试图验证有效的选项输入.

该插件具有result()事件,该事件在进行选择时触发.这没关系,但是当用户点击时我需要检查文本框中的值.所以我们尝试了.change()和.blur()事件,但它们都存在问题:当你点击结果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>
Run Code Online (Sandbox Code Playgroud)

npd*_*oty 9

我认为不是编写自己的函数来验证数据是否匹配,而是可以调用search().如果result()使用null data参数调用,那么您知道未使用自动完成,并且通过调用search()模糊,您可以保证result()至少调用一次.

我已经发布了类似问题的代码,这也可能有所帮助.

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
});
Run Code Online (Sandbox Code Playgroud)


Jos*_*lio 4

更新:这应该有效。我将名称列表加载到名为 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;
}
Run Code Online (Sandbox Code Playgroud)

  • 在这种情况下,正确的方法是让 fetchNames.asp 接受与要验证的名称相同的查询字符串参数。例如:searchNames.asp?name=John .... 如果找到则返回名称,否则返回空白字符串。可以将其添加到 onBlur() 事件中。那有意义吗? (2认同)