Shealan
Shealan

Reputation: 1346

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'.

Upvotes: 0

Views: 2569

Answers (2)

Jamie Rumbelow
Jamie Rumbelow

Reputation: 5095

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");
    });
};

Upvotes: 0

nickytonline
nickytonline

Reputation: 6981

Instead of this.attr("selected", "selected"); do this:

var selectedData = 'GB' // assuming you extracted it from JSON data already

$("option[value='" + selectedData + "']", $(this)).attr("selected", "selected"); // Assuming that "this" is a reference to your picklist.

Upvotes: 1

Related Questions