My form has a list box that asks for the user's country but I only want to populate the list box, via an AJAX call, if the box doesn't already show the user's country. Initially the list box contains just one country - the country returned from a ip-to-country lookup on the server.
It appears that the default action of the list box occurs before my event action. I'd like to have my action occur first so that when the user clicks the list box, the box is pre-populated with the countries pulled off the server before the box opens.
Thanks for any suggestions.
$().ready(function() {
$('select#selCountry').one('click', function() {
var selCountry = $('select#selCountry');
var selected = $(selCountry).val();
selCountry.html('<option value="">Loading...</option>');
$.getJSON('/AjaxHelpers/CountryList', function(data) {
if (data.length) {
var options = '';
for (var i = 0; i < data.length; i++) {
var key = data[i].Key;
var val = data[i].Value;
options += '<option value="' + key + '"';
if (key == selected) {
options += ' selected="selected"';
}
options += '>' + val + '</option>';
}
selCountry.html(options);
}
else {
selCountry.html('<option value="">Failed.</option>');
}
});
});
});
HTML:
<div>
<select id="selCountry" name="CountryCode"><option value="GB">United Kingdom</option>