how can I populate the ASP.NET dropdown with javascript?
javascript doesn't know anything about a server-side language. All he sees is client-side HTML. Javascript can be used to control the DOM. How this DOM was created is not important. So when you talk about the ASP.NET drop-down list, what it actually means is a javascript function, is a client-side HTML <select>
element.
Assuming this element has a corresponding unique id, you can 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);
Note that <%= SomeDdl.ClientID %>
used to retrieve the client ID from the drop-down list generated by ASP.NET. This will only work if javascript is inline. If you use this in a separate javascript file, you will need to define some global variable pointing to the identifier of the drop-down list or just use deterministic identifiers if you are using ASP.NET 4.0.
Here's a live demonstration .
also how can i remove all list items down?
You can set the length of the corresponding <select>
to 0:
document.getElementById('<%= SomeDdl.ClientID %>').length = 0;
And a live demonstration .
source share