Loading ...

jQuery: How to get all selected items of listbox in comma separated string | CodeAsp.Net

jQuery: How to get all selected items of listbox in comma separated string

 /5
0 (0votes)

In this blog I will show how to get all the selected items of ListBox in a comma separated string. I will use jQuery to do it. User will select the items in the ListBox and will click the button and then all those selected items will be displayed in comma separated string in a label. Below is the sample code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">
    </script>

</head>
<body>
    <form id="form1" runat="server">
    Select items and click the button to get the selected items<br />
    <asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple" Width="100px">
        <asp:ListItem Text="Select" Value="-1" />
        <asp:ListItem Value="1" Text="Text1" />
        <asp:ListItem Value="2" Text="Text2" />
        <asp:ListItem Value="3" Text="Text3" />
        <asp:ListItem Value="4" Text="Text4" />
        <asp:ListItem Value="5" Text="Text5" />
    </asp:ListBox>
    <input id="TestButton" type="button" value="Test" /><br />
    <asp:Label ID="TestLabel" runat="server" Text=""></asp:Label>

    <script type="text/javascript">
        $(function() {
            $('#TestButton').click(function() {
                var commaSeparated = $('#<%= ListBox1.ClientID %> option:selected')
                .not('option[value=\'-1\']').map(function() {
                    return this.innerHTML;
                }).get().join(',');

                $('#<%= TestLabel.ClientID %>').html(commaSeparated);
            });
        });
    </script>

    </form>
</body>
</html>

 


Hope this helps!

Comments (no comments yet)

Top Posts