Add new item in dropdown using jquery

In this programming tutorial we will learn how to add new item in dropdown using jquery. It is quite easy in jquery. Let's have a look over the code snippet given below in which i will add a new country in dropdown when button is clicked.
Add new item in dropdown using jquery
before

After
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Add new item in dropdown using jQuery</title>
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $("#btnClick").click(function () {
                var newCountry = $("#txtItem").val();
                if (newCountry.length > 0)
                    {
                    $("#ddlCountry").append($("<option>").val(newCountry).text(newCountry));
                    $("#txtItem").val("");
                   }
            });
        });
    </script>
</head>
<body>
    <div style="font-family:verdana;font-size:12px;">
   New Country: <input type="text" id="txtItem" />
 Country:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;
 <select id="ddlCountry">
 <option value="Pakistan">Pakistan</option>
 <option value="China">China</option>
 <option value="United States">United States</option>
 </select>
        <input id="btnClick" type="button" value=" Add Country " />
    </div>
</body>
</html>

In this above mentioned example, i have a textbox, a dropdown and a button in my page. Country dropdown by default contains three countries which are Pakistan, China and United States. Now for adding new country such as Australia or india, i have written a code in document.ready(), that will execute when button's click event will be fired.
$("#ddlCountry").append($("<option>").val(newCountry).text(newCountry));
The above mentioned code snippet will dynamically add new item or in this example we can say new country to the dropdown using append() function of jquery, which is a built-in function in jquery.

So that's it. This is the way to add new item or element in dropdown using jquery.
I love your feedback.

0 comments: