Home
Go to the LINQ example

Filling the subcategory dropdown via Ajax calls

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.

Live example

JQuery loadJSON plugin enables you to bind a list based on the Ajax responses taken from the server side. In the following example, each time the user select a region, Ajax call loads the related towns from the server and loadJSON plugin loads them into the dropdown list.









Implementation

HTML code is shown in the following listing:

			<label for="Region">Region</label>
			<select name="Region" >
				<option value="" class="regions"></option>
			</select>

			<label for="Town">Town</label>
			<select name="Town" id="Town" multiple="multiple" >
				<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:

			{
				"regions":[
					{
						"value": 1,
						"text": "East Europe"
					},
					{
						"value": 2,
						"text": "West Europe"
					},
					{
						"value": 3,
						"text": "Middle Europe"
					}
				]
			}       
        

The only important thing is that name of the array should match the name of the class in the options tags

Example of JSON object that can be used to fill town list is shown below:

			{
				"towns":[
					{
						"value": 17,
						"text": "Belgrade"
					},
					{
						"value": 18,
						"text": "Buchurest"
					},
					{
						"value": 19,
						"text": "Moscov"
					},
					{
						"value": 20,
						"text": "Kiev"
					}
				]
			}      
        

The only important thing is that name of the array should match the name of the class in the options tags

If the region array is placed in the regions.js file, the following line of code will load the dropdown list:

        $('#Region').loadJSON('regions.js');
        

If the town array is placed in the towns1.js, towns2.js, towns3.js files, the following code will load the towns dropdown list:

        	$('#Region').change(function() {
						var id = $(this).val();
						$('#Town').loadJSON('towns' + id + '.js');
					});
        

When region in the dropdown list is changed, this code taks id of the region and loads town(ID).js array into the towns dropdown.

As you might see, connecting dropdowns is easy with loadJSON plugin.

Go to LINQ example