I have two select boxes: one is country and the other one is cities. When the user selects a country, the appropriate cities for that country should be populated in the "cities" from the database.
I am new to jquery and javascript and i am not sure how to implement this. It will be appreciated if someone gives me a sample code for performing this functionality. I have no idea and i am pretty much stuck as i am new to the scripting languages.
I am using this in one of my forms in django framework which is implemented in python.
Thank you in advance
<!DOCTYPE html>
<html>
<head>
<style>
div { color:red; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<select name="country" id="country">
<option value = "india">india</option>
<option value = "USA">USA</option>
<option value = "UK">UK</option>
<option value = "China">China</option>
<option value = "Sweden">Sweden</option>
<option value = "Germany">Germany</option>
</select>
<select name="cities" id="cities">
<option value = ""></option>
</select>
<div></div>
</body>
</html>
Try this:
In your template
$('#country').change(function() {
var value = $(this).attr('value');
var request = $.ajax({
url: "/getcities/",
type: "GET",
data: {country : value},
dataType: "json",
success: function(data) {
//Popluate combo here by unpacking the json
}
});
});
In your view:
def getcities(request)
if request.method == "GET":
country = request.GET["country"]
cities = Cities.objects.filter(country=country)
results = [{'city': str(city.name), 'id':city.id} for city in cities]
json = simplejson.dumps(results)
return HttpResponse(json, mimetype='application/json')
You will have to map the url /getcities/ to your view in urls.py.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.