jQuery:验证至少一项 select 在 ListBox 中完成

jQuery: Validate atleast one item select done in ListBox

这是列表框和按钮。

<asp:ListBox ID="lbTOAddress" runat="server"></asp:ListBox>
<asp:Button ID="btnSend" runat="server" Text="Send"/>

它有三项。在按钮单击事件期间,我想验证,至少必须使用 jQuery 在 ListBox 中选择一项。请提出建议。

Using JQuery

if($('select option:selected').length > 0) { //do something }

你可以这样试试:

 if ($('#lbTOAddress').val() != null) {
        // user has selected at least one value
    }

请试试这个

     <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.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("[id*=btnGetValues]").click(function () {
                  if ($('#lbTOAddress').val() != null) {
                // user has selected at least one value

            }
            else

                alert('Please select item from list.');
            });
        });   
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ListBox ID="lbTOAddress" runat="server" Width="150" Height="60" SelectionMode="Multiple">
            <asp:ListItem Text="Mango" Value="1"></asp:ListItem>
            <asp:ListItem Text="Apple" Value="2"></asp:ListItem>
            <asp:ListItem Text="Banana" Value="3"></asp:ListItem>
            <asp:ListItem Text="Guava" Value="4"></asp:ListItem>
            <asp:ListItem Text="Pineapple" Value="5"></asp:ListItem>
            <asp:ListItem Text="Papaya" Value="6"></asp:ListItem>
            <asp:ListItem Text="Grapes" Value="7"></asp:ListItem>
        </asp:ListBox>
        <br />
        <hr />
        <asp:Button ID="btnGetValues" Text="Get values" runat="server" />
    </div>
    </form>
</body>
</html>

这样使用,

if ($('select option:selected')) {
  // something
} else {
  // else something
}