Reputation: 1264
I need the user to type a country in a field but a country can be named in various ways (ie: "Moldova", "Republic of Moldova", "Moldova, Republic of"...).
This can lead to a mess in no time. So I decided to compare the user input against an array of "official names" and use jQuery autocomplete to solve that problem.
Now, if the user types "Moldova", a selection box pops up and let him select the proper syntax.
But nothing prevents him from going with "Moldova" alone as the autocompletion is a suggestion that the user can bypass by not clicking on it.
I don't want that as it eventually leads to a mess just as well, so I searched and found a solution here:
jquery autocomplete field that REQUIRES a selected value?
and it looks like this:
$("#country").autocomplete(
{
source: mycountries
change: function(event, ui)
{
if (!ui.item)
{
$("#country").val("");
}
}
});
This is nice as it clears the field if the user didn't select the autocomplete suggestion, this way, the user can't possibly validate his form until he has the proper syntax for the country.
But it still has a major flaw:
Let's say the user types "France", which matches the array of names, BUT decided to write it all by himself, without clicking on the field suggesting it:
it will be cleared just the same when the user leaves the field.
So, how can I make this script working by not clearing the field if the user own entry matches the suggestion?
Upvotes: 0
Views: 158
Reputation: 1264
I (think I) found it:
change: function(event, ui)
{
var myval=$("#country").val();
if($.inArray(myval,mycoutries) == -1)
{
$("#country").val("");
}
}
So far, so good.
Upvotes: 1