Tuesday, April 15, 2008

How To Add Edit Delete Item In ListBox

This program used to add,edit and remove the item in the listbox control, this code can be used for both the serverside control and also for clientside control.

JavaScript Part:
Add Item To ListBox:

             function addItem()
{
var lst = document.getElementById('lstbox'); // listbox control id
var newItem = prompt("Enter New Item","Enter Value Here");
                      //Option object is created for every option in a selection
//new Option([text[, value[, defaultSelected[, selected]]]]) // Syntax
                      if(newItem == null)
{
return false;
}
else
{
lst.options[lst.length] = new Option(newItem,newItem,false,false);
return false;
}
}
Edit Item To ListBox:
             function editItem()
{
var lst = document.getElementById('lstbox'); // listbox control id
var selVal = lst.value;
if(selVal != "")
{
var newItem = prompt("Enter New Item",selVal);
if(newItem == null)
{
return false;
}
else
{
lst.options[lst.selectedIndex] = new Option(newItem,newItem,false,false);
return false;
}
}
else
{
alert('Select Item From The List To Edit ');
}
}
Remove Item For The Listbox

function rmItem()
{
var lst = document.getElementById('lstbox');// listbox control id
var selVal = lst.value;
if(selVal != "")
{
var msg = confirm("Do You Want To Remove ( "+selVal+" ) From The List");
if(msg == true)
{
lst.options[lst.selectedIndex] = null;
}
}
else
{
alert('Select Item To Remove From The List');
}
return false;
}




HTML Part

<div>

<select id="lstbox" multiple=multiple style="width:100px; overflow:auto;">

</select>

<input type="button" id="btnAdd" value="Add" onclick="return addItem();" />

<input type="button" id="btnEdit" value="Edit" onclick="return editItem();" />

<input type="button" id="btnDel" value="Delete" onclick="return rmItem();" />

</div>

Programe Demo

1 comment:

Laura Bush said...

I found decent information in your article.validate email list I am impressed with how nicely you described this subject, It is a gainful article for us. Thanks for share it.