5

how can I populate an ASP.NET dropdownlist using javascript? also how can I clear all dropdownlist items?

thanks

1
  • dropdown is rendered as select html control,so you can use simple javascript to populate it document.getElementById('dropdownname').options.add(new Option('text', 'value')) Commented Dec 10, 2011 at 18:06

1 Answer 1

8

how can I populate an ASP.NET dropdownlist using javascript?

javascript knows nothing about server side language. All it sees is client side HTML. Javascript could be used to manipulate the DOM. How this DOM was generated is not important. So when you talk about ASP.NET dropdownlist, what it actually means to a javascript function is a client side HTML <select> element.

Assuming this element has a corresponding unique id, you could add <option> to it:

var select = document.getElementById('<%= SomeDdl.ClientID %>');
var option = document.createElement("option");
option.value = '1';
option.innerHTML = 'item 1';
select.appendChild(option);

Notice how <%= SomeDdl.ClientID %> is used to retrieve the client id of the dropdown list generated by ASP.NET. This will only work if the javascript is inline. If you use this in a separate javascript file you will have to define some global variable pointing to the id of the dropdown list or simply use deterministic ids if you are using ASP.NET 4.0.

Here's a live demo.

also how can I clear all dropdownlist items?

You could set the length of the corresponding <select> to 0:

document.getElementById('<%= SomeDdl.ClientID %>').length = 0;

And a live demo.

Sign up to request clarification or add additional context in comments.

1 Comment

You could probably update this to have '<%: DropDown1.ClientID %>' instead of 'id_of_select', of course assuming the control was called DropDown1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.