Friday, September 30, 2011

Cascading dropdown Implementation using jQuery

Cascading dropdown functionality is common requirement in every web application. Implementing cascading dropdown in JavaScript is very lengthy and takes lot of effort to use AJAX calls .

With jQuery you can write in simple way to achieve this. Here is the code for populate  the state dropdown based on the country dropdown selected value.

 <script language="javascript" type="text/javascript">
        $(document).ready(function () {
            $(document).ready(function () {
                $("#ddlCountry").change(function () {
                    var selectedItem = "";
                    selectedItem = $(this)[0].value; // get the selected ddlCountry id
                    var url = '/Home/AsyncGetStateList/?countryId=' + selectedItem;
 
                    $.get(url, function (data) {       // call controller's action
                        $("#ddrStates").empty();
                        $.each(data, function (index, optionData) {
                            $("#ddrStates").append("<option value='"
                            + optionData.Text
                            + "'>" + optionData.Value
                            + "</option>");
                        });
                    });
                });
 
            });
 
        });
    </script>

New optimized code


The above code has totally 21 lines. This we can optimize to 12 lines. Here is the code.


 



 <script language="javascript" type="text/javascript">
        $(document).ready(function () {
            $("#ddlCountry").change(function () {
                $.getJSON("/Home/AsyncGetStateList", { countryId: $("#ddlCountry option:selected").val() }, function (data) {
                    $("#ddrStates").empty();
                    $.each(data, function (index, optionData) {
                        $("#ddrStates").append("<option value='"
                                           + optionData.Text
                                          + "'>" + optionData.Value
                                           + "</option>");
                    });
                });
            });
        });
 
    </script>