October 1, 2025

Filter Dropdownlist Based on Another Dropdownlist with JQuery

In this short tutorial, I will show you an easy way to load a second dropdownlist based on selection on another dropdownlist. We would be using example from FleetMs v2.

We’ll cover:

 

The Scenario

We would like to add a location information. So in the Add Location form, there are two dropdownlists:

  • the select country dropdown
  • the select state dropdown

We want such that when a country is selected from the from the select country dropdownlist, the state dropdownlist loads the states in the selected country. This is shown below:

Filter states dropdownlist based on selected country
Filter states dropdownlist based on selected country

To achieve this we would take the steps below:

 

Step 1 – Write the GetCountryById Method

In the CountryController file, you need to write a method that returns a single country as json object. See the function below:

//The Get Country By Id
@GetMapping("/parameters/country/{id}")
@ResponseBody
public Country getCountry(@PathVariable Integer id){
    return countryService.getById(id);
}

 

Step 2 – Write the JavaScript Code

You need to write the code that would handle the change event of the select list of the country. The complete code is given below:

$('document').ready(function () { // Line 1
    $('#ddlCountryAdd').on('change',function () { // Line 2
        $('#ddlStateAdd').empty().append('<option value="null">-SELECT-</option>'); // Line 3
        var countryid = $(this).val(); //Line 4
        var href = "http://localhost:8080/parameters/country/" + countryid //Line 5
        $.get(href, function (country, status) { // Line 6
            var states = country.states; // Line 7
            for (var i = 0; i <= states.length-1; i++) { // Line 8
                $('#ddlStateAdd').append('<option value="' + states[i].id + '">' + states[i].name + '</option>'); // Line 9
            }
        })
    })
})

 

Explanation

  • Line 2 – The change event executes a function when the first select is clicked (ddlCountryAdd)
  • Line 3 – Clear existing content of the existing content of the ddlState list
  • Line 4 – Retrieve the selected country id
  • Line 5 – The url to retrieve a country by id
  • Line 6 – Make a get request to the url to retrieve the selected country details
  • Line 7 – Get the states attribute of the selected country
  • Line 8 – Loop through the list of states
  • Line 9 – Set the dropdownlist values and text using the state data

 

Another Approach

Another option would be to have a method in the countryController to return list of states by country. So I’ll leave that up to you as a home work.

Video series on this can be found here. 

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments