How to Clear and Repopulate Your ASP.NET DropDown List with jQuery
Yes you can call and use your ASP.NET controls from jQuery! Shereen has already posted a blog on how you can access these controls JQuery Accessing the Client Generated ID of ASP.NET Controls so feel free to check it out there first.
Recently we’ve had to create a UI that has a datepicker, and the date that a user selects should determine what values get populated in an ASP.NET dropdown.
Here’s how we did it
We’ve listed below the two controls we’re using in this example: a calendar control and an asp.net drop down list.
1 2 | <input id="datepicker" type="text" /> <asp:DropDownList ID="ddlDates" runat="server" Width="100px"></asp:DropDownList> |
For the date picker, we used the DatePicker control from jQueryUI. Their demos and documentation are a great starting point, if you have any troubles with the calendar on your site, drop us a line.
Next, we had to add the following references:
1 2 | <script src="http://myserver/js/jquery-1.3.2.min.js" type="text/javascript"></script> <script src="http://myserver/js/jquery-ui-1.7.1.custom.min.js" type="text/javascript"></script> |
Then we wired it up! Good ol’ jQuery!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | function PopulateDropDownDates(dateText, numDaysToAdd) { var selectedDate = new Date(dateText); //clear the dropdown $("#<%= ddlDates.ClientID %>>option").remove(); //add todays date $("#<%= ddlDates.ClientID %>").append($('<option></option>').val(dateText).html(dateText)); //counter for (var i = 0; i <= numDaysToAdd; i++) { var currentDate = new Date(selectedDate.getFullYear(), selectedDate.getMonth(), selectedDate.getDate() + i); currentDate = currentDate.getMonth() + 1 + "/" + currentDate.getDate() + "/" + currentDate.getFullYear(); $("#<%= ddlDates.ClientID %>").append($('<option></option>').val(currentDate).html(currentDate)); } } $(document).ready(function() { $("#datepicker").datepicker({ onSelect: function(dateText, inst) { PopulateDropDownDates(dateText, 14); } }); |
Voila! That’s it. Works beautifully!
Tags: ASP.NET, jQuery, sharepoint