How do I add an option to a dropdown list using jQ

2019-06-14 23:44发布

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"));

5条回答
▲ chillily
2楼-- · 2019-06-15 00:09

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?

查看更多
唯我独甜
3楼-- · 2019-06-15 00:09

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.

查看更多
乱世女痞
4楼-- · 2019-06-15 00:10

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.

查看更多
放我归山
5楼-- · 2019-06-15 00:17

What if you change it to

$("#ddlCategory").append($("<option></option>").attr("value", "1").text("Some Text"));
查看更多
Luminary・发光体
6楼-- · 2019-06-15 00:26
var newOption = "<option value='"+"1"+"'>Some Text</option>"; 
$("#ddlCategory").append(newOption);
查看更多
登录 后发表回答