info: Fix state select box not updating when country is changed.
[org.fsf.memberdashboard.git] / assets / js / member-info.js
index aaf093707c4171de73c463be616acfe4ef1f98d4..53711dc978f170f225ca6471fc06ccae2a36cfd6 100644 (file)
  */
 
 (function($) {
+  // Helper function to support older versions of jQuery that don't
+  // parse the JSON returned from AJAX calls by default.
+  function parseJSONMaybe(obj) {
+    return _.isString(obj) ? JSON.parse(obj): obj;
+  }
+
   function loadProfile(gid, success) {
     $.get('/civicrm/profile/edit', {
       gid: gid,
@@ -46,9 +52,7 @@
         .value();
     }
 
-    // Support older versions of jQuery that don't parse the JSON by
-    // default.
-    profile = _.isString(profile) ? JSON.parse(profile): profile;
+    profile = parseJSONMaybe(profile);
     var form = $('<form' + profile.attributes + '></form>');
 
     form.append(profile.requirednote)
     $('#info-form').append(form);
   }
 
+  // Fetch states/provinces via AJAX.
+  function watchForCountryChanges() {
+    // TODO: Fetch these ids from the profile JSON.
+    var countryId = "#country-Primary, #country-1";
+    var stateProvinceId = "#state_province-Primary, #state_province-1";
+    var url = "/civicrm/ajax/jqState";
+
+    $(countryId).change(function() {
+      $.get(url, {
+        _id: $(this).attr('id'),
+        _name: $(this).attr('name'),
+        _value: $(this).val()
+      }, function(states) {
+        var stateSelect = $(stateProvinceId);
+
+        function addOption(key, value) {
+          stateSelect.get(0).add(new Option(key, value));
+        }
+
+        states = parseJSONMaybe(states);
+        stateSelect.empty();
+
+        if(_.isEmpty(states)) {
+          addOption('- select a country -', '');
+        } else {
+          _.each(states, function(state) {
+            // Civi 4.4 use value, Civi 4.5+ uses key.
+            if(state.key) {
+              addOption(state.value, state.key);
+            } else {
+              addOption(state.name, state.value);
+            }
+          });
+        }
+      });
+    });
+  }
+
   $(document).ready(function() {
-    loadProfile(memberDashboard.profileId, renderProfile);
+    loadProfile(memberDashboard.profileId, function(profile) {
+      renderProfile(profile);
+      watchForCountryChanges();
+    });
   });
 })(jQuery);