简体   繁体   中英

populate ASP.NET dropdownlist using javascript

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

thanks

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM