Add TextBox value to DropDownList or Html SELECT using jQuery

You have a dropdownlist or an HTML Select with you. You now want to add additional options to the SELECT which you enter in the textbox, on the click of a button.
Here's how to do so using jQuery. The same technique can also be used for an ASP.NET DropDownList without causing a postback.


<html xmlns="http://www.w3.org/1999/xhtml">


<head runat="server">


<title></title>


<script src="Scripts/jquery-1.2.6.js" type="text/javascript"></script>


<script type="text/javascript">


    $(document).ready(function() {


        $("#Button1").click(function() {


            $('#Select1').append($("<option>" + $('#Text1').val() + "</option>"));


            return false;


        });


    });    


</script>


</head>


<body>


<form id="form1" runat="server">


<div>


    <select id="Select1" name="Select1">


        <option>Option1</option>


        <option>Option2</option>


        <option>Option3</option>


        <option>Option4</option>


    </select>


    <input id="Text1" type="text" />


    <input id="Button1" type="submit" value="button" />


</div>


 


</form>


</body>


</html>







About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.