jQuery:验证在ListBox中选择完成的至少一个项目

时间:2015-08-06 06:30:52

标签: jquery asp.net validation button listbox

这是ListBox和Button。

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

它有三个项目。在Button click事件期间,我想验证,必须使用jQuery在ListBox中选择至少一个项目。请建议。

4 个答案:

答案 0 :(得分:2)

请试试这个

     <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>

答案 1 :(得分:0)

  

使用JQuery

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

答案 2 :(得分:0)

您可以尝试这样:

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

答案 3 :(得分:0)

像这样使用,

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