I want to build a Country/State selector. First you choose a country, and the States for that country are displayed in the 2nd select box. Doing that in PHP and jQuery is fa
Based on Mike's suggestion:
// the jQuery
$(function () {
var $country = $('.country');
var $provInput = $('.province');
var $provSelect = $('').insertBefore($provInput).change(function() {
$provInput.val($provSelect.val());
});
$country.change(function() {
$provSelect.empty().addClass('loading');
$.getJSON('/get-provinces.json', {'country':$(this).val()}, function(provinces) {
$provSelect.removeClass('loading');
for(i in provinces) {
$provSelect.append('');
}
$provSelect.val($provInput.val()).trigger('change');
});
}).trigger('change');
});
# the form
country = CharField(initial='CA', widget=Select(choices=COUNTRIES, attrs={'class':'country'}))
province = CharField(initial='BC', widget=HiddenInput(attrs={'class':'province'}))
# the view
def get_provinces(request):
from django.utils import simplejson
data = {
'CA': CA_PROVINCES,
'US': US_STATES
}.get(request.GET.get('country', None), None)
return HttpResponse(simplejson.dumps(data), mimetype='application/json')