JQuery loadJSON plugin can be used to dinamically fill dropdown based on the selected item in primary dropdown. This is common usage in the applications where you have primary list (e.g.categories or countries) and you need to dinamically populate secondary dropdown.
JQuery loadJSON plugin enables you to bind a list based on the JSON array of objects. In this example local variables containing the arrays of regions and towns will be used to dinamicaly populate region and town dropdown lists. Each time user changes region, the town array will be filtered by the regionid and loaded into the secondary dropdown. For filtering is used JQuery LINQ library but this is just an option.
HTML code is shown in the following listing:
<label for="Region">Region</label> <select name="Region" > <option value="-1" class="regions">Pleaase select</option> </select> <label for="Town">Town</label> <select name="Town" id="Town"> <option class="towns" >-</option> </select>
Classes "regions" and "towns in the option tags are used to map option elements that wil be populated with the JSON object that will be loaded into the HTML form shown above should have properties that matches name attributes of the elements above. Example of JSON object that can be used to fill region list is shown below:
aoRegions = [ { "value": 1, "text": "East Europe" }, { "value": 2, "text": "West Europe" }, { "value": 3, "text": "Middle Europe" } ];
Example of JSON object that can be used to fill town list is shown below:
aoRegions = [ { "value": 17, "text": "Belgrade" "regionid": "1" }, { "value": 18, "text": "Berlin" "regionid": "2" }, { "value": 19, "text": "London" "regionid": "3" }, { "value": 20, "text": "Paris" "regionid": "3" } ] }
Each town has regionid property that will be used for filtering.
The following line of code will load the dropdown list:
$('#Region').loadJSON({ "regions":aoRegions });
Note that original array is wraped into the object with "regions" property in order to match this property with the "regions" class in the option template.
The following code will load the towns dropdown list when region is changed:
$('#Region').change(function() { var id = $(this).val(); var queryResult = $.Enumerable.From(aoTowns) .Where(function (town) { return town.regionid == id }) .OrderByDescending(function (town) { return town.text }) .ToArray(); $('#Town').loadJSON({ "towns": queryResult} ); });
When region is changed, id of the region is taken from the region select list, towns with that region id are filtered from the original array, and they are ordered by text property.
Back to the list