Q:

Selecting a dropdown value based on JSON data

I am trying to build a simple jquery plugin that queries a geolocation system and returns data about where the users IP is based, preselecting it in an HTML form.
I have an HTML select with all the country codes in as values. I need to select the one referenced in the returned data. This is what I have so far...
(function($){

    $.fn.geoselect = function() {

        $.getJSON('http://www.geoplugin.net/json.gp?jsoncallback=?', function(data) {
            this.attr("selected", "selected");
        });

    };

})(jQuery);

Obviously this wont work currently as 'this' related to the select as a whole, not one of its options. If the data returned is 'GB' for example, I need to select the option with a value of 'GB'.

A:

You're inside $.getJSON, so this isn't going to refer to your select. Instead, save it to a variable in the parent scope and then access it in the callback. You can then use the .find() method to get the specific <option> tag.
I'm also going to assume that the data you're getting back from the API is data['geoplugin_city']
$.fn.geoselect = function() {
    var dropdown = this;

    $.getJSON('http://www.geoplugin.net/json.gp?jsoncallback=?', function(data) {
        $(dropdown).find('option[value="' + data['geoplugin_city'] + '"]').attr("selected", "selected");
    });
};

