jQuery Autocomplete verify selected value

点点圈 提交于 2020-01-10 07:50:09

问题


We are using the autocomplete jQuery plugin written by Jörn Zaefferer, and are trying to verify a valid option is entered.

The plugin has result() event which fires when a selection is made. This is OK, but I need to check the value in the textbox when a user clicks out too. So we have tried a .change() and .blur() events, but they both pose an issue: when you click on an entry in the results div (the 'suggest' list) the .change() and .blur() events fire, and this is before the plugin has written a value to the textbox, so there is nothing to verify at this point.

Could someone help me configure events so whenever someone clicks away, but not in the results box I can check for a valid value in the box. If this is the wrong approach please inform me of the correct one. We originally went with this plugin because of its 'mustMatch' option. This option doesn't seem to work in all cases. Many times a valid entry will be written into the textbox and then cleared by the plugin as invalid, I have not been able to determine why.

Basic Code example:

<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>

回答1:


I think rather than writing your own function to verify if the data matches, you can just call search(). If result() is called with a null data parameter, then you know that auto-complete wasn't used and by calling search() on blur, you're guaranteed to get result() called at least once.

I've posted this code for a similar question, it may help here as well.

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
});



回答2:


UPDATE: This should work. I am loading the list of names into an Array called ListOfNames, this is used in the onBlur() event to verify the name entered against the data. You may need to do some tweaks, but I think it should do what you're looking for.

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;
}



回答3:


This is the code I have used in the past. Very clean and simple.

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;
        }
      }
});



回答4:


I use a global data structure to keep track of the values that were found

var ac_sent = {};

the .result() event handler is called before the .change() event handler, so in .result( event, data, formatted ) I add the data to the structure:

ac_sent[ data ] = true;

then in the .change( event ) event handler I check to see if there is an item at ac_sent[ data ], and if there isn't any, I know that the word was not found:

$( "#textbox" ).change( function( event ) {

  var data = event.target.value;

  if ( !ac_sent[ data ] ) {
    // result was not found in autocomplete, do something...
    ac_sent[ data ] = true;  // remember that we processed it
  }

  return false;
});


来源:https://stackoverflow.com/questions/797969/jquery-autocomplete-verify-selected-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!