Reputation: 17421
When I run the following JS I always get the confirm box popping up despite the list visibly having items.
<asp:ListBox ID="list" runat="server" Width="135px" Rows="8" />
function CheckListEmpty() {
if ($("#list").length == 0) {
if (confirm("Are you sure?")) {
//they clicked OK so save and close
return true;
}
else {
//do nothing they hit cancel.
return false;
}
}
else
return true;
}
What am I doing wrong?
Upvotes: 0
Views: 873
Reputation: 4470
The runat="server" causes ASP.NET to dynamically create a unique ID, not the one you assigned. Therefore the ID jQuery selector does not find it. Either add a class and select that or "[id*='ListBox']" to find the ID that contains the ID you specified.
Upvotes: 1
Reputation: 12220
$(document).ready(function() {
...
});
Always best to place your functions inside this to ensure that the DOM is ready
Upvotes: 0
Reputation: 14851
"length" is not a parameter on SELECT elements in javascript. You can use (select).elements.length
instead.
Upvotes: 0
Reputation: 887767
$("#list").length
returns the number of elements matched by the jQuery selector.
It isn't matching anything because you aren't using the ListBox's ClientId
; you need to change it to $("#<%= list.ClientId %>")
.
To get the number of items in the <select>
, you need to write $("#<%= list.ClientId %> option").length
Upvotes: 3