Dependent Auto Suggest with jQuery

by Vincy. Last modified on July 6th, 2023.

Auto-suggest feature for a form field will reduce the user’s effort while entering input data. In this post, we will see how to auto-suggest a dropdown field depending on the result of another dropdown.

In a previous post, we have seen how to create a dependent dropdown and a 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

HTML Dependent Dropdown

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

dependent-auto-suggest-with-jquery

<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

This jQuery code has 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, the jQuery script will check if any keyword match is found in the 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

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page