18

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"));
Kurt McKee
  • 1,410
  • 13
  • 17
DenaliHardtail
  • 27,362
  • 56
  • 154
  • 233
  • $("") is not a valid selector... Please read how to use selector in jquery... – Guillaume Cisco Nov 03 '11 at 15:10
  • try this one if you like to use javascript http://chiragrdarji.wordpress.com/2007/06/06/add-items-in-drop-down-list-or-list-box-using-javascript/ – huMpty duMpty Nov 03 '11 at 15:16
  • This will not make it get stored in viewstate. Be sure you are not relying on normal postback behavior /viewstate if you do this. If you are, then you should expose a web method instead and call it asynch. – Nikki9696 Nov 03 '11 at 15:32

5 Answers5

13
var newOption = "<option value='"+"1"+"'>Some Text</option>"; 
$("#ddlCategory").append(newOption);
Bryan Denny
  • 27,363
  • 32
  • 109
  • 125
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
9

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?

Community
  • 1
  • 1
Jason
  • 15,915
  • 3
  • 48
  • 72
0

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.

user369142
  • 2,575
  • 1
  • 21
  • 9
0

What if you change it to

$("#ddlCategory").append($("<option></option>").attr("value", "1").text("Some Text"));
Milan Jaric
  • 5,556
  • 2
  • 26
  • 34
0

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.

Community
  • 1
  • 1
arb
  • 7,753
  • 7
  • 31
  • 66