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: /
How do I set the drop-down to show the user's country ?
thanks
Thomas
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/E7fBk/
How do I set the drop-down to show the user's country ?
thanks
Thomas
Share Improve this question asked Nov 4, 2013 at 16:37 ThomasDThomasD 2,4947 gold badges40 silver badges59 bronze badges2 Answers
Reset to default 6Try
$(function () {
$.get("http://ipinfo.io", function (response) {
$('#countryCode option[data-countryCode="' + response.country + '"]').prop('selected', true)
}, "jsonp");
});
Demo: Fiddle
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");
});
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745627718a4636910.html
评论列表(0条)