How to add items list in dropdown list using jquery - Cascading drop down

If you want to create 2 dropdown lists in which the second dropdown value will depend on the selected value from the first dropdown, you need to Implement JSON + Webservice+ JQuery.

In my solution, I will use Jquery Ajax to request data from web service and add value to the second dropdown.

Scenario

Let say the first dropdown will list all Country, and the second dropdown will list all state from the selected country.

Solution

  1. Create JSON Webservice, you can refer to this link
  2. Create custom JQuery function to handle onChange event on dropdown list country.
  3. Use return value from web services to the second dropdown items list.

Full Code Example

Note: The web service will use from the post here

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            //product item 1
            $("#dropdownCountry").change(function (e) {
                var obj1 = { Country: $("#dropdownCountry").val() };
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "http://localhost:3323/AjaxWebService.asmx/getState",
                    data: JSON.stringify(obj1),
                    dataType: "json",
                    success: function (data1) {
                        var appenddata1 = "";
                        //alert(data1.d);
                        var jsonData1 = JSON.parse(data1.d);
                        for (var i = 0; i < jsonData1.length; i++) {
                            appenddata1 += "<option value = '" + jsonData1[i].SHORT_NAME + " '>" + jsonData1[i].FULL_NAME + " </option>";
                        }
                        $("#dropdownState").append(appenddata1);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <select id="dropdownCountry">
        <option>Select Country</option>
        <option>Malaysia</option>
    </select>

    <select id="dropdownState">
        <option>Select State</option>       
    </select>
</body>
</html>



Popular posts from this blog

Example to disable save as certain file type in SSRS Report Viewer

How to create DataGrid or GridView in JSP - Servlet

Control Webpart Visible/Enable using macro in Kentico