-
Notifications
You must be signed in to change notification settings - Fork 6
/
jQuery.geoselector.js
59 lines (49 loc) · 1.62 KB
/
jQuery.geoselector.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
(function ($) {
$.fn.geoSelector = function (options) {
var settings = $.extend({
countrySelector: "*[name='country']",
stateSelector: "*[name='state']",
data: "divisions.json",
defaultCountry: "Australia",
defaultState: "Western Australia",
}, options);
var countries = $(settings.countrySelector, this);
var states = $(settings.stateSelector, this);
if (countries.length != 1) {
throw "Unexpected number of country selectors";
}
if (states.length != 1) {
throw "Unexpected number of state selectors";
}
$.getJSON(settings.data, function (data) {
var country = $("<select />").attr("name", countries.attr("name"));
var state = $("<select />").attr("name", states.attr("name"));
$.each(data.countries, function (code, name) {
var option = $("<option />").text(name).attr("code", code).appendTo(country);
if (settings.defaultCountry == name) {
option.attr("selected", "selected");
}
});
var updateStates = function (code, def) {
state.empty();
if (data.divisions[code] && data.divisions[code].length) {
$.each(data.divisions[code], function (i, name) {
var option = $("<option />").text(name).appendTo(state);
if (def == name) {
option.attr("selected", "selected");
}
});
} else {
$("<option />").text(" ").appendTo(state);
}
};
countries.replaceWith(country);
states.replaceWith(state);
updateStates($("option:selected", country).attr("code"), settings.defaultState);
country.change(function () {
updateStates($("option:selected", this).attr("code"));
return true;
});
});
};
})(jQuery);