Javascript to Get all Selected Values or Text from a Multiple Select Listbox of Asp.Net C# VB.Net

ListBox is a popular Asp.Net Control to create a nice and superb user interface (UI). The ListBox control provides us very sophisticated ways to implement our requirement. Getting Selected Items or Selected Values or Selected Text of a ListBox control from server side is so much easy but not so much easy from client side like Javascript. In this article I will describe how we can nicely use the ListBox control to get all or multiple Selected Items or Selected Text or Selected Values using a simple Javascript Method.

Related Article:
Jquery to Get all Selected Values or Text from a Multiple Select Listbox of Asp.Net C# VB.Net

Objective:
Javascript to Get all Selected Values or Text from a Multiple Select Listbox of Asp.Net Csharp VB.Net

To do the Example Prepare the HTML markup like below:

    <asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple" Width="100" Height="200">
        <asp:ListItem Text="January" Value="1" />
        <asp:ListItem Text="Februray" Value="2" />
        <asp:ListItem Text="March" Value="3" />
        <asp:ListItem Text="April" Value="4" />
        <asp:ListItem Text="May" Value="5" />
        <asp:ListItem Text="June" Value="6" />
        <asp:ListItem Text="July" Value="7" />
        <asp:ListItem Text="August" Value="8" />
        <asp:ListItem Text="September" Value="9" />
        <asp:ListItem Text="October" Value="10" />
        <asp:ListItem Text="November" Value="11" />
        <asp:ListItem Text="December" Value="12" />
    </asp:ListBox>
    <br /><br />
    <asp:Button ID="Button1" runat="server" Text="Get All Seleted Items"  OnClientClick="return GetAll()"  />
    <hr />
    <br />
    <asp:Label ID="lbl_Get_All_Selected_Items" runat="server" Text=""></asp:Label>

Javascript Code to get all Selected Values from a Multiple Selection Mode ListBox Control:

<script type="text/javascript">
function GetAll() {

    var sel = document.getElementById('<%= ListBox1.ClientID %>');
    var optsLength = sel.options.length;
    var lbl = document.getElementById('<%= lbl_Get_All_Selected_Items.ClientID %>');
    lbl.innerHTML = '';
    for (var i = 0; i < optsLength; i++) {
        if (sel.options[i].selected) {
            lbl.innerHTML +='Selected Value: ' + sel.options[i].value + " Selected Text: " + sel.options[i].text + "<br/>";
        }
    }
    return false;
}
</script>

Now run the project hope you will get all desired values.

Download Code Example C#        Download Code Example VB.Net

Posted in .Net, Asp.net, C#, Client, Javascript, ListBox, VB.Net

Leave a Reply

Your email address will not be published. Required fields are marked *

AlphaOmega Captcha Classica  –  Enter Security Code
     
 

*