Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 684
Ali_dotNet Avatar asked Dec 10 '11 17:12

Ali_dotNet


People also ask

How do I bind a DropDownList in JavaScript?

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.


1 Answers

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.

like image 181
Darin Dimitrov Avatar answered Sep 20 '22 00:09

Darin Dimitrov