Wednesday, December 24, 2008

DropDownList Add/Remove Item Using Javascript

In this post i will discuss operations such as insert/Add and remove item from DropDownList using javascript. I have used insert and remove operation to add and remove items from dropdownlist using javascript in my projects very often. And i think it is good to share my knowledge regarding this operation with you people as well. First i will discuss how you can remove all the items from the dropdownlist and then how you can add item in the dropdownlist using javascript.

Removing Items from DropDownList

Below is the simple code to remove the items from the dropDownList. In the code below i have created a simple function name clearDropwDownList , the function will take the dropDownList control object as parameter.

function clearDropDownList(dropDownList)
{
//get the total item from the dropDownList
var intTotalItems= dropDownList.options.length;
//loop through the number of items
for(var intCounter=intTotalItems;intCounter>=0;intCounter--)
{
//remove the intCounter( currently index) item from the dropDownList
dropDownList.remove(intCounter);
}
}

At the first line of the function i have declared variable named intTotalItems which will hold the number of items in the dropDownList which is passed to the function. Then i use the for loop to remove the each item in the dropDownList by using the remove(intCounter), statement where intCounter is the current index to be removed.

Add Items from DropDownList

Now how to add new value(s) in the dropDownList, below is the code you can use to add the value to the dropDownList, i have created function for this operation as well, so you need to pass the dropDownList control object , the value field and the text field to be added in the dropDownList as new item.

function addDropDownListItem(dropDownList,value,Text)
{
//Create new item option to be added in the dropDownList
var newOption = document.createElement("option");
//assign Text value to the text property of the option object
newOption.text = Text;
//assign value to the value property of the option object
newOption.value = value;
//add new option in the dropDownList
dropDownList.options.add(newOption);
}

First i have created the option object to hold the text and the value of the new item and then i assign the values to the text and the value property and at the end added the new option in the dropDownList.

If you have any question regarding this post please ask me

Happy programming :)

2 comments:

equivoc said...

Also consider:

while (dropDownList.hasChildNodes()) {
dropDownList.removeChild(dropDownList.firstChild);
}

or:

dropDownList.innerHTML = '';

Regards
equivoc

Asim said...

equivoc: Thanks for your comments and nice suggestion regarding the removal of the items from the Dropdownlist , its really nice.