Sometimes, we will provide options to the users to select items from a ListBox and add it to another i.e. there will be a list of options available in a source ListBox in which the users have to select their options and add those to the target ListBox control. This can be implemented in javascript by iterating the source Listbox's item and move the item to target ListBox if it is selected.
Refer the following script to implement the same.
function Add()
{
var source = document.getElementById('ListBox1');
var target = document.getElementById('ListBox2');
var count = source.length;
for (var i = count - 1; i >= 0; i--)
{
var item = source.options[i];
if(item.selected)
{
source.remove(i);
target.add(item);
}
}
}
function AddAll()
{
var source = document.getElementById('ListBox1');
var target = document.getElementById('ListBox2');
var count = source.length;
for (var i = count - 1; i >= 0; i--)
{
var item = source.options[i];
source.remove(i);
target.add(item);
}
}
function Remove()
{
var source = document.getElementById('ListBox2');
var target = document.getElementById('ListBox1');
var count = source.length;
for (var i = count - 1; i >= 0; i--)
{
var item = source.options[i];
if(item.selected)
{
source.remove(i);
target.add(item);
}
}
}
function RemoveAll()
{
var source = document.getElementById('ListBox2');
var target = document.getElementById('ListBox1');
var count = source.length;
for (var i = count - 1; i >= 0; i--)
{
var item = source.options[i];
source.remove(i);
target.add(item);
}
}
ASPX
<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
</asp:ListBox>
<input type="button" OnClick="Add()" value="Add" />
<input type="button" OnClick="AddAll()" value="Add All" />
<input type="button" OnClick="Remove()" value="Remove" />
<input type="button" OnClick="RemoveAll()" value="Remove All" />
<asp:ListBox ID="ListBox2" runat="server" SelectionMode="Multiple"></asp:ListBox>
|