【问题标题】:jQuery: Validate atleast one item select done in ListBoxjQuery:验证在 ListBox 中完成的至少一项选择
【发布时间】:2015-08-06 06:30:51
【问题描述】:

这是列表框和按钮。

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

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

【问题讨论】:

  • 你介意使用asp.net的RequiredFieldValidator吗?
  • 是的。我想要它在 jQuery 中。

标签: jquery asp.net validation button listbox


【解决方案1】:

请试试这个

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

【讨论】:

  • 如果可以通过检查null直接检查,为什么还要去for循环?
  • 点击按钮时这个没有调用。
【解决方案2】:

使用 JQuery

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

【讨论】:

    【解决方案3】:

    你可以这样试试:

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

    【讨论】:

      【解决方案4】:

      这样使用,

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

      【讨论】:

      • 这里指的是 HTML 中的选择框
      • 我们不想在那里提供列表框 ID?
      • 如果你有选择框/列表框的 id,你可以在那里提供 id
      猜你喜欢
      • 1970-01-01
      • 2011-03-13
      • 2015-11-06
      • 1970-01-01
      • 1970-01-01
      • 2012-10-17
      • 1970-01-01
      • 2012-09-30
      • 2017-09-09
      相关资源
      最近更新 更多