CODEDIGEST
Home » CodeDigest
Search
 

Technologies
 

Add,Add All, Remove, Remove All functionalities from one ASP.Net ListBox to another in Javascript
Submitted By Satheesh Babu B
On 11/21/2008 7:36:02 AM
Tags: ASP.Net,CodeDigest,JavaScript  

 

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>

Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!

Recent Codes
  • View All Codes..