Search code examples
jqueryasp.netlistbox

Determine if an ASP.NET ListBox Item is Selected Using jQuery


I have the following function which will iterate through all of the items in my ASP.NET ListBox upon being clicked:

$('#<%=MyListBox.ClientID %>').children("option").each(function () {

}

I do not want this function above to change because for the outer function I need to loop through all items to process some logic. However internally I need to see if the item in focus is selected or not and can't get it correct. I've searched a ton of posts that can make the function only return selected items, but I want a check to see if the current item in this function is checked.

I tried:

if ($(this).selected())

...and that threw an error stating object not supported. I also tried:

if ($(this).selected == true)

...and it said selected was undefined, yet when I look at $(this) the value of selected is false.

How can I check within my function to see if the current item in the loop is selected?


Solution

  • I figured this out in how to determine if the option value is selected. I used the prop() method from jQuery as shown below:

    $('#<%=MyListBox.ClientID %>').children("option").each(function () {
        if ($(this).prop('selected'))
        {
           //Do work here for only elements that are selected
        }
    }