Dependent Auto Suggest with jQuery

Auto-suggest feature for a form field will reduce user’s effort while entering input data. In this post, we are going to see how to do auto suggest for a dropdown field depends upon the result of another dropdown. In a previous post, we have seen how to create dependent dropdown and dropdown with auto suggest, separately.

In this post we have two dropdowns with auto-suggest and search features. On changing the first dropdown option we call jQuery to load the dependent option results for the send drop down. The dependency is found based on the keyword match.

View Demo

dependent-auto-suggest-with-jquery

HTML Dependent Dropdown

This code contains drop-down fields for the country and country-dependent information. The options to these dropdowns will be load by using jQuery select2.

<div id="frm-dropdown">
	<select id="country" style="width:250px;">
	<option>Choose Country</option>
	<!-- Country List -->
	</select>
	<select id="country_info" style="width:250px;">
	<option>Select</option>
	<!-- Country - Dependent List -->
	</select>
</div>

Auto Suggesting Dependent Results using jQuery

In this jQuery code, we have two arrays containing option values for the dropdowns. One is the list of counties and the other is the list of country-based information.

While selecting a country, jQuery script will check if any keyword match is found in the array containing country-based information array. Then the matched results will be pushed to the suggested list.

<script type="text/javascript">
	$(document).ready(function() {
		var country = ["Australia", "Bangladesh", "Denmark", "Hong Kong", "Indonesia", "Netherlands", "New Zealand", "South Africa"];
		$("#country").select2({
		  data: country
		});
		var country_info = ["Australian Open Tennis", "Tourism Australia","Australian Election","Denmark Flag","Study in Denmark"];
		loadCountryInfo(country_info);
		
		$("#country").on("change",function() {
			var selected_country = $(this).val();
			var selected_country_info = [];
			$.each(country_info, function( key, value ) {
			  if(value.indexOf(selected_country)!= -1) {
			  selected_country_info.push(value );
			  }
			});
			$('#country_info').empty();
			loadCountryInfo(selected_country_info);
		});
	});
	function loadCountryInfo(country_info) {
		$("#country_info").select2({
		  data: country_info
		});
	}
</script>

View DemoDownload

This jQuery code tutorial was published on June 14, 2016.

↑ Back to Top