I'm using jQuery UI autocomplete for data entry into an input field with the values being pulled from a database via ajax. That is all normal autocomplete.
However, the user can enter values that are not in the database and I wonder how to handle it.
I'm trying to avoid another ajax call to the database on change of the field to check if the data is new or not. Since I use autocomplete so often I would have to code many such checks.
If I know the data is new, I can give the user options whether to add it to the DB or it notify them of error input.
Maybe there's a notification from autocomplete that the user entered a new value.
Or maybe there's a way to restrict the user only to dropdown data. (that would cause other issues I think)
Or maybe somebody has a better idea.
Related questions (or maybe I should post these separately)
How do I trigger an autocomplete to open as soon as the user tabs into an empty field? Setting the number of minLength to zero still requires the user to at least hit the down arrow.
Can I trigger the dropdown programmatically, such as from the image of a down arrow.
开发者_高级运维Thanks
Try the close
event. (http://docs.jquery.com/UI/Autocomplete#event-close), the autocomplete closes if there is nothing found. You can probably look at the event to see what caused the close, and if it was an XHR it should mean that the autocomplete was closed caused by no items found. Can't guarantee it'll work, but it's probably worth a shot.
You can create a custom source function like this:
$("field").autocomplete({
source: function(request, response) {
fetchFromDB(request.term, function(data) {
// if data.length == 0 it was not in DB
response(data);
});
}
});
With fetchFromDB being whatever you are using now to get the results.
As for triggering autocomplete, you could do something like:
$("field").focus(function(event) {
var e = $.Event("keydown.autocomplete");
e.keyCode = $.ui.keyCode.DOWN;
$("field").trigger(e);
});
This should work, I used similar code to auto-trigger selection of the first element in autocomplete drop down.
精彩评论