From: David Thompson Date: Fri, 14 Nov 2014 20:10:36 +0000 (-0500) Subject: info: Fix state select box not updating when country is changed. X-Git-Tag: v0.1~17 X-Git-Url: https://vcs.fsf.org/?a=commitdiff_plain;h=59b55e97f075d99d3c9b633c66dbd5b06c1d9edb;p=org.fsf.memberdashboard.git info: Fix state select box not updating when country is changed. * assets/js/member-info.js: Watch country select box for changes and fetch relevant states via AJAX. --- diff --git a/assets/js/member-info.js b/assets/js/member-info.js index aaf0937..53711dc 100644 --- a/assets/js/member-info.js +++ b/assets/js/member-info.js @@ -20,6 +20,12 @@ */ (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.append(profile.requirednote) @@ -59,7 +63,48 @@ $('#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);