1

I want to get all the listitems that exist in a listbox using jquery, it does not matter if selected or not.

Here is my client side script:

<asp:ListBox ID="lstSelected" runat="server" SelectionMode="Multiple" Rows="10">
    <asp:ListItem Value="Employee_OID">EID</asp:ListItem>
    <asp:ListItem Value="EmpID">Emp ID</asp:ListItem>
    <asp:ListItem Value="Employee_Name">Name</asp:ListItem>
</asp:ListBox>
faizanjehangir
  • 2,771
  • 6
  • 45
  • 83
  • Since you are using the traditional .Net (runat="server"), be careful about the timeframe of your data. Implementing this as others have suggested will only be good "POST" FACTO – Pinch Oct 22 '12 at 14:01

5 Answers5

6

By adding a static ID (ClientIDMode="Static") generation to the ListBox, you could use the ID property value in jQuery directly (skipping ClientID usage):

<asp:ListBox ID="lstSelected" runat="server" SelectionMode="Multiple" Rows="10" ClientIDMode="Static">
    <asp:ListItem Value="Employee_OID">EID</asp:ListItem>
    <asp:ListItem Value="EmpID">Emp ID</asp:ListItem>
    <asp:ListItem Value="Employee_Name">Name</asp:ListItem>
</asp:ListBox>

jQuery to get all options:

$('#lstSelected option')

jQuery to get all selected options:

$('#lstSelected option:selected')

See more info here on the ClientIDMode: http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientidmode.aspx

krembanan
  • 1,408
  • 12
  • 28
  • That did the trick...I need the values and text in csv format..any help on that? – faizanjehangir Oct 22 '12 at 13:58
  • There are better answers for this if you search stackoverflow, but look into the .val() and .text() methods to get the value and text of options. For example: http://stackoverflow.com/questions/880293/jquery-get-remaining-option-values-in-csv-format – krembanan Oct 25 '12 at 08:16
1

To get the element client side you're going to need to use the ClientID property of the ListBox:

All Options

$("#<%=lstSelected.ClientID %> option");

All Selected Options

$("#<%=lstSelected.ClientID %> option:selected");
hunter
  • 62,308
  • 19
  • 113
  • 113
1

I wasn't able to comment on neurotix's answer cause of reputation.. wanted to share though this worked for me just needed to put $() around "this".

$('#lstSelected option').each(function(){


if($(this).val() == anyvalue)

//your code here

});
hackingchemist
  • 156
  • 1
  • 11
0

I guess this should do the trick:

$('#lstSelected option').each(function(){


if(this.val() == anyvalue)

//your code here

});
mike
  • 550
  • 2
  • 9
  • 24
0
$("#<%= lstSelected.ClientID %>").find("option");
Louis Ricci
  • 20,804
  • 5
  • 48
  • 62