how can I populate an ASP.NET dropdownlist using javascript? also how can I clear all dropdownlist items?
thanks
1. Get my source(datatable) in format "Key1-Value1|Key2-Value2|........" keep it in hiddenfield. 2. Then in javascript parse this string iterate and create Option object and fill dropdown by getting it by ID.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With