views:

1957

answers:

3

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>

+1  A: 

You will have no joy cross browser with the select click event. Only the change event is supported by all therefore you need to rethink.

One option would be is to use a label which shows the ip country and if the user wants to change it they click a button next to the label which then creates & populates a select and replaces the label.

redsquare
A: 

the line

$('select#selCountry').one('click', function() {

is what's postponing the Ajax call until you click on the box. Try changing it to simply

$(function(){

or just removing that line and its closing brace.

Chris Tek
A: 

This would be much better you just had something like:

County: Spain change

When they click change, replace the country name with a drop down box of all the countries.

Jason Christa
errr is that not what I said!
redsquare
cool idea, someone should post example code!
jasondavis