2

I have a select dropdown containing a list of countries looking something like this:

<select name="countryCode" id="countryCode">
<option data-countryCode="GB" value="44" Selected>UK (+44)</option>
<option data-countryCode="US" value="1">USA (+1)</option>
<optgroup label="Other countries">
    <option data-countryCode="DZ" value="213">Algeria (+213)</option>
    <option data-countryCode="AD" value="376">Andorra (+376)</option>
</optgroup>
</select>

I then look up the user's country using ipinfo.io and would like to set the selected option based on the returned country and the data-countryCode attribute. I have tried some different approaches, but I simply cannot get it to work.

I have created a jsfiddle with the country-selector and the lookup: http://jsfiddle.net/E7fBk/

How do I set the drop-down to show the user's country ?

thanks

Thomas

2 Answers 2

6

Try

$(function () {
    $.get("http://ipinfo.io", function (response) {
        $('#countryCode option[data-countryCode="' + response.country + '"]').prop('selected', true)
    }, "jsonp");
});

Demo: Fiddle

Sign up to request clarification or add additional context in comments.

Comments

2

Fiddle DEMO

$(function () {
    $.get("http://ipinfo.io", function (response) {
        $('#countryCode option[data-countryCode="' + response.country + '"]').prop('selected', true)
    }, "jsonp");
});

or

Fiddle DEMO

$(function () {
    $.get("http://ipinfo.io", function (response) {
        $('#countryCode').val($('#countryCode [data-countryCode="' + response.country + '"]').val());
    }, "jsonp");
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.