arsenal
arsenal

Reputation: 24154

Match the two letter country code to predefined array of country code

I am trying to get the country code of the user's current location using Javascript. With the code, I have, I will be getting two letter country code and then I need to match that two letter country code with my predefined array to get the three letter country code.

Below is my code, but it is not working as soon as I added my predefined array things for three letter country code. none of my alert box are working now.

<html>
    <head>
        <title>Get web visitor's location</title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script>

    var threeLtrCC.US = 'USA';
    var threeLtrCC.IN = 'IND';

$(document).ready( function() {

    $.getJSON( "http://smart-ip.net/geoip-json?callback=?",
        function(data){
            alert( data.countryCode);
            var cc = threeLtrCC[data.countryCode];
            var countryCode=data.countryCode

            alert(cc);
            $('#newURL').attr('href','https://www.google.com&jobid='+countryCode);
        }
    );
}); 

    </script>

    </head>
    <body>
<hr/>

<a id="newURL">url</a>

    </body>
</html>

It is not alerting me anything. Suppose if the country code is US, then it should get matched with my predefined array and print it out as USA.

What wrong I am doing?

Upvotes: 1

Views: 1553

Answers (2)

krishwader
krishwader

Reputation: 11371

You seem to be declaring two variables with this line:

var threeLtrCC.US = 'USA';
var threeLtrCC.IN = 'IND';

Not adding anything to an object of name threeLtrCC. You have to declare threeLtrCC and then:

var threeLtrCC = {}
threeLtrCC.US = 'USA';
threeLtrCC.IN = 'IND';

or even

var threeLtrCC = {"US": 'USA', "IN" : 'IND'}

Demo : http://jsbin.com/ucifup/1/edit

Upvotes: 1

SoWhat
SoWhat

Reputation: 5622

this is wrong

var threeLtrCC.US = 'USA';
var threeLtrCC.IN = 'IND';

you cannot declare a property of an object

var threeLtrCC={IN:"IND",US:"USA"};

Upvotes: 1

Related Questions