jorexe
jorexe

Reputation: 187

JQuery Autocomplete with countries

i'm trying to make an autocomplete with country codes in jquery. I'm using this code as example. In my site, it works really well, but the values, appear as a list in front of the input, and not like the example in the site. I couldn't run it on jsfiddle, but here is my code. Thanks you!

var countries = {
    "Argentina (AR)":"AR",
    "United States (US)":"US",
    "Comoros": "KM",
    "Congo (Brazzaville)": "CG",
    "Congo, Democratic Republic of the": "CD",
    "Cook Islands":  "CK",
    "Costa Rica":  "CR",
    "Côte d'Ivoire": "CI",
    "Croatia": "HR",
    "Cuba":  "CU",
    "Cyprus":  "CY",
    "Czech Republic":  "CZ",
    "Denmark": "DK",
    "Djibouti":  "DJ",
    "Dominica":  "DM",
    "Dominican Republic":  "DO",
};

$( "#countryCodes" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
            if ( event.keyCode === $.ui.keyCode.TAB && $( this ).autocomplete( "instance" ).menu.active ) {
                event.preventDefault();
            }
        })
.autocomplete({
        minLength: 0,
        source: function( request, response ) {
            // delegate back to autocomplete, but extract the last term
            response( $.ui.autocomplete.filter(
            Object.keys(countries), extractLast( request.term ) ) );
        },
        focus: function() {
            // prevent value inserted on focus
            return false;
        },
        select: function( event, ui ) {
            var terms = split( this.value );
            // remove the current input
            terms.pop();
            // add the selected item
            terms.push( countries[ui.item.value] );
            // add placeholder to get the comma-and-space at the end
            terms.push( "" );
            this.value = terms.join( "," );
            return false;
        }
    });

Upvotes: 0

Views: 1249

Answers (2)

Thangaraja
Thangaraja

Reputation: 956

exactLast function is missing in the fiddle. I added now and here now it works in Fiddle

function extractLast( term ) {
      return split( term ).pop();
    }

https://jsfiddle.net/px2dmd1o/1/

Check and let me know what is your issue

Upvotes: 1

mulleady1
mulleady1

Reputation: 301

One solution is to provide the autocomplete with a source array. jQuery's autocomplete expects the source array to contain objects with properties label and value. You could build this array after defining your countries object, e.g.:

var mySource = Object.keys(countries).map(function(country) {
  return { 
    label: country, 
    value: countries[country] 
  };
});

...and then provide that to the autocomplete:

$('#countryCodes').autocomplete({
  source: mySource
});

To get your fiddle running I had to comment out the rest of what you were passing to the autocomplete widget because it had some undefined functions.

Upvotes: 0

Related Questions