Git Product home page Git Product logo

country-select-js's Introduction

Country Select JS

A jQuery plugin for selecting a country, based on the excellent International Telephone Input plugin. It adds a flag dropdown to any input, which lists all the countries in English and the predominant national language next to their flags.

alt tag

Table of Contents

Demo

Try it for yourself using the included demo.html.

Features

  • Automatically select the country as the user types
  • Navigate the country dropdown by typing a country's name, or using up/down keys
  • Selecting a country from the dropdown will update the country name in the input
  • Dropdown appears above or below the input depending on available space/scroll position
  • Lots of initialisation options for customisation, as well as public methods for interaction
  • Can optionally update a related field with the two-letter ISO country code on selection

Getting Started

  1. Download the latest version

  2. Link the stylesheet (note that this references the image flags.png)

<link rel="stylesheet" href="build/css/countrySelect.css">
  1. Add the plugin script and initialise it on your input element
<input type="text" id="country">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="build/js/countrySelect.min.js"></script>
<script>
  $("#country").countrySelect();
</script>
  1. Optional: add an extra input field (with type hidden or text) named the same as your selector input appended with "_code". This will automatically be updated with the ISO 3166-1 alpha-2 code for the selected country.
<input type="text" id="country" />
<input type="hidden" id="country_code" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="build/js/countrySelect.min.js"></script>
<script>
  $("#country").countrySelect();
</script>

Options

Pass an (optional) object as a parameter to the countrySelect method when initializing the selector.

$("#country").countrySelect({
  defaultCountry: "jp",
  onlyCountries: ['us', 'gb', 'ch', 'ca', 'do', 'jp'],
  preferredCountries: ['ca', 'gb', 'us'],
  responsiveDropdown: true
});

Note: any options that take country codes should be lower case ISO 3166-1 alpha-2 codes

defaultCountry
Type: String Default: ""
Set the default country by it's country code. Otherwise it will just be the first country in the list.

onlyCountries
Type: Array Default: undefined
Display only the countries you specify. Takes an array of country codes.

excludeCountries
Type: Array Default: undefined
Display only the countries not specified. Takes an array of country codes.

preferredCountries
Type: Array Default: ["us", "gb"]
Specify the countries to appear at the top of the list.

responsiveDropdown
Type: Boolean Default: false
Set the dropdown's width to be the same as the input. This is automatically enabled for small screens.

localizedCountries
Type: Object Default: {}
Allows to translate the countries by its given iso code e.g.:

{ 'de': 'Deutschland' }

Public Methods

destroy
Remove the plugin from the input, and unbind any event listeners.

$("#country").countrySelect("destroy");

getSelectedCountryData
Get the country data for the currently selected flag.

var countryData = $("#country").countrySelect("getSelectedCountryData");

Returns something like this:

{
  name: "Afghanistan (‫افغانستان‬‎)",
  iso2: "af",
}

selectCountry
Change the country selection (e.g. when the user is entering their address).

$("#country").countrySelect("selectCountry", "gb");

setCountry
Insert a country name, and update the selected flag accordingly.

$("#country").countrySelect("setCountry", "United States");

Static Methods

getCountryData
Get all of the plugin's country data.

var countryData = $.fn.countrySelect.getCountryData();

Returns an array of country objects:

[{
  name: "Afghanistan (‫افغانستان‬‎)",
  iso2: "af",
}, ...]

setCountryData
Set all of the plugin's country data.

$.fn.countrySelect.setCountryData(countryData);

Troubleshooting

Image path
Depending on your project setup, you may need to override the path to flags.png in your CSS.

.country-select .flag {background-image: url("path/to/flags.png");}

Full width input
If you want your input to be full-width, you need to set the container to be the same i.e.

.country-select {width: 100%;}

Input margin
For the sake of alignment, the default CSS forces the input's vertical margin to 0px. If you want vertical margin, you should add it to the container (with class country-select).

Displaying error messages
If your error handling code inserts an error message before the <input> it will break the layout. Instead you must insert it before the container (with class country-select).

Dropdown position
The dropdown should automatically appear above/below the input depending on the available space. For this to work properly, you must only initialise the plugin after the <input> has been added to the DOM.

Contributing

Contributions and improvements to the library are welcome! For instructions on contributing to a project on Github, see this guide: Fork A Repo.

If you are treating the library as a Node package, the following will be relevant to you.

To start a local devserver with source code live reload install the dependencies with:

$ npm install

And run:

$ gulp

To transpile the scss source, minify and prepare your changes at src to build run:

$ gulp build

Attributions

country-select-js's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

country-select-js's Issues

Selectbox

Why we not use selectbox instead of input field

Setting new country data didn't effect

I tried to customize countries data as I need multi languages in my website so I need to translate countries' names.
What I did is:
var countrySelect = $(" .country_selector").countrySelect({ defaultCountry: "tr", preferredCountries: ['tr', 'fr', 'ro', 'sp', 'sa', 'eg'] }); var countries = []; $.getJSON('countries.json', function(results){ $.each(results, function(index, country){ countries.push({name: country.n, iso2: country.i}); }); $.fn.countrySelect.setCountryData(countries); }).fail( function(d, textStatus, error) { console.error("getJSON failed, status: " + textStatus + ", error: "+error) });
Nothing happened and if I console.log(allCountries) where the setCountryData is defined it shows my new list but the front-end didn't apply it.

Adding languages

Is there an option or possibility to add languages? So you would get

  • Belgium(Dutch)
  • Belgium(French)

Does not work with jQuery 3.1.1

Drop down is missing flags and countries when using jQuery 3.1.1

Error:

    jquery.min.js:4 Uncaught TypeError: a.indexOf is not a function
r.fn.load @ jquery.min.js:4
(anonymous function) @ countrySelect.min.js:1
(anonymous function) @ countrySelect.min.js:1
(anonymous function) @ countrySelect.min.js:1
..... Uncaught TypeError: $(...).countrySelect is not a function(anonymous function) @

Add build tool config

Allow easier contribution by rearranging the source into a separate directory from the build and provide a means for authors to build locally. This will open up the ability to more easily test, as well.

Styling the dropdown

can anyone tell me how to customize the flags dropdown like selected flag size, dropdown button and sth else? Suppose i want it to look like this
untitled

Please add this to you css file,

Please add this to you css file, on my bootstrap css the text apeared below the flag.

<style> .country-select input { margin-bottom: 0 !important; margin-top: 0 !important; position: relative; z-index: 0; ----- > padding-left: 50px; } </style>

Certain country codes do not convert to country names

The function $("#country").countrySelect("selectCountry", "gb"); does not work appropriately for all countries. For example, gb, cy, ca work fine, but cz, ec do not for some reason....?

I should not the code forms part of a Laravel application, where the country code value is set in a separate hidden input field, and a JQuery script is used to set the country in the country selector. So only with certain countries does it set the name appropriately, but not with others...

Support "auto" as a default country with geoIP lookup

The International Telephone Input plugin that this one is based on supports a defaultCountry option of "auto", which prompts it to perform a geoIP lookup on the client browser and select the current country as the default.

This also necessitates the addition of a geoIpLookup parameter, which provides a function to actually perform the lookup. The assumption here is that a geo-location plugin is already installed (or will be installed to supply this feature), and an appropriate function to invoke it is easy to supply.

This requires both supporting this feature in the first place, and also providing enough information in the documentation to allow users to supply their own lookup function.

On blur country and country_code inputs can be out of sync

You update the country val on blur based on the flag, but I think you should also update the country_code hidden input then. Otherwise, if you type something wrong and then blur, the name will be "fixed" but the code will remain empty... Hope all this makes sense...

Cheers!

Update bower file

Could you update the bower file to also include the css file please so we don't have to overwrite it on our bower.

Feature request: empty country selection

One more for today :)
It seems to me there is no straightforward way to "clear" the selection, so that after submitting the form the country value is "empty". The same goes for starting without any country selected.

Am I missing something? If not, how hard would it be to add this possibility?

Update version at npm

Would be good to have the recent changes available at npm, and since we have a visual change at the flags a major version bump is a good choice.

Add country's currency

Wouldn't it be cool if the country's currency would be retrieved via getSelectedCountryData() method?

Crash on open with invalid selected item

If I create a text field with value like "123", call $('#myelement').countrySelect(), the select will appear correctly, but opening the dropdown will crash on

[Error] TypeError: undefined is not an object (evaluating 'element.offset().top')
_scrollTo (countrySelect.js, line 418)
_showDropdown (countrySelect.js, line 231)
(anonymous function) (countrySelect.js, line 209)
dispatch (jquery-1.10.2.min.js, line 2)
handle (jquery-1.10.2.min.js, line 2)

I propose to add the following to _scrollTo()

if (!element || !element.offset()) {
  return;
}

Automatically Update Input on Lose Focus

The user is allowed to type on the input and a country is automatically selected from the left.
The form submit however takes into consideration the value on the input field. This gives wrong submission since for example:

  1. A user types in "ger"
  2. The Germany flag is automatically selected on the dropdown
  3. The term "ger" is saved on the database

There are of course many alternatives to overcome this problem but it would be brilliant to have the input filled with the correct name of the country once the user leaves that input.

Citizenship support

I would highly recommend you to add citizenship countries as an improvement for this plugin.

Thank you

"responsiveDropdown" parameter has no effect

Hi there,

I found out that your written parameter "responsiveDropdown" doesn't work at all. It doesn't work because it doesn't even exists in the javascript files or somewhere. I exactly need your plugin with the behaviour you have written in your Readme and it would be great if you could add that feature.

Thanks, Alex

Initialization with a filled field containing parenthesis fails

Line 332: the value is retrieved as-is. It may contains () such as : "Greece (Ελλαδα)". Theses parenthesis seems to be interpreted as special characters in the RegExp and this country name does never match with the existing entry.
Just replaced line 332 with : var value = this.countryInput.val().replace(/(?=[() ])/g, ''); found here : http://stackoverflow.com/questions/22872974/javascript-regex-to-escape-parentheses-and-spaces

I'am not sure if the space escaping is really necessary, thought...

select by native name

Hi,

I'm wondering, why it is not possible to "search" by the native name of countries.

For example, some of my german users type in "deutschland", but instead "Germany (Deutschland)", the countrySelect selects "Denmark". At the end, it results in an empty post, because no existing country is selected.

How can we fix this?

how to use getSelectedCountryData ?

i need to get the country iso for the selected country i must add onchange attribute somewhere
`<script>
jQuery(document).ready(function () {
jQuery("#country_selector").countrySelect({
defaultCountry: "dz",
//onlyCountries: ['us', 'gb', 'ch', 'ca', 'do'],
preferredCountries: ['dz', 'fr', 'uk']
});

            });

            $('li.country').click(function () {
                var iso = $(this).attr('data-country-code');
                alert(iso);
            });

            var countryData = $("#country_selector").countrySelect("getSelectedCountryData");

        </script>`

defaultCountry bug

I have two dropdowns for countrySelect and I set the defaultCountry to 'ph' but only the first dropdown implemented the default. I used their class as a selector on instantiating countrySelect. any idea on this?

Make _showDropdown public

Hi,
thanks for such a nice plugin. Due to the input box (which is gr8 btw), the user has to click the flag to see the list. We have found idiot users find it hard to figure where to click.

What would be very useful, is some way to toggle() this via and external API. So developers can use their own UX to invoke your drop-down.

I saw the code and realized _showDropdown was one such method that could be public, or maybe have a pair showList(), hideList() that makes this possible.

If you feel its useful and is a quick fix for you, please do it. If not, Id be happy to try and contribute :)

defaultCountry does not work

Please check if defaultCountry works. I think it doesn't work.

defaultCountry
Type: String Default: ""
Set the default country by it's country code. You can also set it to "auto", which will lookup the user's country based on their IP address. Otherwise it will just be the first country in the list.

I use the following and it does not work:

$("[id$=country]").countrySelect({
    defaultCountry: function(callback) {
        $.get('http://ipinfo.io', function() {}, "jsonp").always(function(resp) {
            var countryCode = (resp && resp.country) ? resp.country : "";
            console.log(countryCode);
            countryCode.toLowerCase();
            callback(countryCode);
        });
    }
});

and the following:

$("[id$=country]").countrySelect({
    defaultCountry: 'auto',
    geoIpLookup: function(callback) {
        $.get('http://ipinfo.io', function() {}, "jsonp").always(function(resp) {
            var countryCode = (resp && resp.country) ? resp.country : "";
            console.log(countryCode);
            countryCode.toLowerCase();
            callback(countryCode);
        });
    }
});

selectCountry not working

Hi
thaks for your code
$("#country").countrySelect("selectCountry", "US");
not working
give me error
type error : b is null

Multilanguage countries should show all their names

I don't know if this is the only case but for countries where languages coexist with same legal status (and not just by majority of speakers) it would be reasonable to use the all language names for them

Example:

Switzerland (Schweiz/Suisse/Svizzera)
instead of Switzerland (Schweiz)

Issue on page reload

There seem to be an error when using the CountrySelect plugin.

jQuery.Deferred exception: n is undefined
TypeError: n is undefined

The issue occurs on page reload button click only.

(Jquery 3.1.1 & Mozilla 58)

Npm or/and bower

Hey,

nice work. Did you consider to create package for bower and npm ?

tag id contains dots

Hi,

Great extension. I am using it in a project where the element ids contain dots and jQuery does not like them.

so I escape them using the standard way:

jQuery("#user\\.attributes\\.country").countrySelect();

in order to initiate the countrySelect. Although this fails with the _code field.

I suggest a change where by one can pass in an additional id to define where to store the code for the country. Also to remain backwards compatible. Perhaps you could also escape dots ->
when you are looking for the element in the code ->

		this.countryCodeInput = $("#"+this.countryInput.attr("id")+"_code");

What do you think ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.