I'm trying to use the following code to add an option to a dropdown list in ASP.NET. Any ideas why this doesn't work? I tried Googling but can't figure out why this won't work.
What shoud the code do? I have an ASP.NET dropdown list. I want to access the dropdown list by name and add an item to the list. The item should have descriptive text of "Some Text" and a value of "123".
Thanks!
$("#ddlCategory").append($("<option>Some Text</option>").val(1).html("123"));
var newOption = "<option value='"+"1"+"'>Some Text</option>";
$("#ddlCategory").append(newOption);
You can try
$("#ddlCategory").append($("<option value='123'>Some Text</option>");
Or
$('#ddlCategory').
append($("<option></option>").
attr("value", "123").
text("Some Text"));
2nd code snippet from this question What is the best way to add options to a select from an array with jQuery?
Have you tested that 1) your jquery is correct and works in a flat HTML file and 2) that you are using the correct Id - ASP.NET changes Ids dynamically on elements that runat="server", so you might want to try:
$('#<%=ddlCategory.ClientID%>').append(...etc etc
That will get you the correct Id from the ASP.NET page class.
What if you change it to
$("#ddlCategory").append($("<option></option>").attr("value", "1").text("Some Text"));
Trying to add options to an ASP.Net dropdown list with client-side code is a bad idea. It introduces all sorts of postback problems. See this link for more details. You should either populate the dropdown completely client side, or trigger a partial postback to fill the list.