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")); 
3
  • $("<option>Some Text</option>") is not a valid selector... Please read how to use selector in jquery... Commented Nov 3, 2011 at 15:10
  • try this one if you like to use javascript chiragrdarji.wordpress.com/2007/06/06/… Commented Nov 3, 2011 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. Commented Nov 3, 2011 at 15:32

5 Answers 5

13
var newOption = "<option value='"+"1"+"'>Some Text</option>"; $("#ddlCategory").append(newOption); 
Sign up to request clarification or add additional context in comments.

1 Comment

This worked. I also changed from using the control ID to using a class name. The selector change did not work by itself.
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?

1 Comment

i would use .val(123) instead of .attr("value", "123")
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.

1 Comment

Remembered that during debug. I'm now using a class selector instead of id.
0

What if you change it to

$("#ddlCategory").append($("<option></option>").attr("value", "1").text("Some Text")); 

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.