Last active
November 9, 2022 19:22
-
-
Save salsalabs/8d2fb759d01465855d57 to your computer and use it in GitHub Desktop.
Javascript to change the list of states when a country changes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script type="text/javascript"> | |
// Workaround to change the value of `State` select options from `CC+XX` to the | |
// state name. Bogus values will not show up in supporter records -- A Good Thing. | |
// | |
// @note The Salsa-provided `change` event handler is unbound by this code. It's | |
// the one that plants bogus values in the `State` select options, and doesn't | |
// need to run. To make this happen correctly, this script must appear *just before* | |
// the </body> tag in your template. | |
// | |
// @see https://help.salsalabs.com/entries/23796550 | |
// | |
// @dependencies jQuery, any version | |
// | |
$(document).ready(function() { | |
// This script only runs if there is a Country field on the page. | |
var country = $('select[name=Country]'); | |
if (country.length == 0) return; | |
if ($('select[name=State]').length == 0) return; | |
var organizationKey = $('*[name=organization_KEY]').val(); | |
country.unbind('change'); | |
country.change(function() { | |
var countryCode = $('select[name=Country]').val(); | |
if (countryCode == null || countryCode.trim().length == 0) { | |
return; | |
}; | |
$("select[name=State]").empty(); | |
var url = "/o/" + organizationKey + "/p/salsa/common/international/public/country/eng/countryData.sjs?country=" + countryCode + "&jsoncallback=?" | |
$.getJSON(url, function(data) { | |
$("select[name=State]").append("<option value>Select a state or province</option>"); | |
data.states.map(function(state) { | |
// Note that the name won't replace the code for US states because | |
// none of the official state abbreviations have numbers. | |
if (RegExp('\\d+').test(state.code)) { | |
state.code = state.name; | |
} | |
$("select[name=State]").append("<option value='" + state.code + "'>" + state.name + "</option>"); | |
return state; | |
}); | |
}); | |
}); | |
// Set the default country code to the United States (US). | |
$("select[name='Country']").val('US').change(); | |
// Make the state prompt less US-centric. | |
$('*[name=State] option:first').text('Select a state or province'); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment