Tuesday, 21 January 2014

How to append dropdownlist using jquery

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

In my solution i will create the JSON Webservice , and I will use Jquery Ajax to request data from webservice and append the value to the second dropdown.

Scenario

Let say the first dropdown will list all Country, and the second dropdown will list all state from 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. Bind return value from webservice to the second dropdown.

Full Code Example

Note : The webservice 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>



By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)

0 comments:

Post a Comment

Subscribe to our newsletter to get the latest updates to your inbox.

Your email address is safe with us!




Founder of developersnote.com, love programming and help others people. Work as Software Developer. Graduated from UiTM and continue study in Software Engineering at UTMSpace. Follow him on Twitter , or Facebook or .



Powered by Blogger.