【问题标题】:jquery script to check if textbox is blank, or checkbox is checkedjquery脚本检查文本框是否为空,或者复选框是否被选中
【发布时间】:2018-10-23 20:28:23
【问题描述】:

我正在使用客户端 ID 来检查文本框是否为空白,这在我的脚本中有效,但是在检查复选框是否被选中时,它没有做任何事情

这是我的脚本

 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>  
    <script type="text/javascript">  
        $(function () {
            $('#<%=lbtnSave.ClientID %>').click(function () {
                var txt = $('#<%=txtPhotoAndVideoConsentIfNot.TextBoxID %>');

                if ((txt.val() != null && txt.val() != '')) {
                    alert('filled in');
                } else {
                    alert('empty ');
                }

                if $('#<%= cbPhotoAndVideoConsent.ClientID %>').is(':checked') {
                    alert("TEst");
                }

            })
        });
    </script>  

对按钮、文本框和复选框使用客户端 ID。复选框的 IF 有效,但另一个无效。

我的目标是,我有一个包含文本框和复选框的表单,用户必须填写其中一个

感谢帮助

【问题讨论】:

  • 为什么要加载 jQuery 两次?删除一个,并考虑加载一个更新的。另请单击&lt;&gt; sn-p 编辑器并提供不带任何 ASP 的minimal reproducible example。这不是一个 ASP 问题。此外,您的脚本仅在页面加载时检查字段。以后不会了
  • 有可能两次加载 jquery 会导致问题。
  • @marco - 哦,对了,关于如何勾选复选框和文本框的任何想法?

标签: jquery asp.net vb.net


【解决方案1】:

多个问题:

  • 删除加载 jquery 的一行
  • 没有 TextBoxID 属性
  • if 语句周围缺少 () 括号
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">  
  $(function () {
      $('#<%=lbtnSave.ClientID %>').click(function () {
          var txt = $('#<%=txtPhotoAndVideoConsentIfNot.ClientID %>'); //fix ClientID

          if ((txt.val() != null && txt.val() != '')) {
              alert('filled in');
          } else {
              alert('empty ');
          }
          if ($('#<%= cbPhotoAndVideoConsent.ClientID %>').is(':checked')) { //add parenthesis here
              alert("TEst");
          }
      })
  }
</script>

要捕获这些错误,只需在浏览器中按 F12 键打开开发者工具并观察控制台窗口。这将向您打印出 javascript 错误。

//编辑: 如果你想结合这两个条件,简单地这样做:

if ((txt.val() != null && txt.val() != '') && $('#<%= cbPhotoAndVideoConsent.ClientID %>').is(':checked')) {
    alert('filled in');
} else {
    alert('empty ');
}

【讨论】:

  • 效果更好!我现在正在尝试加入 2 个 if 语句来检查两者 - 沿着 -- if ((txt.val() != null && txt.val() != '') && $('#').is(':checked') == true) {..}
  • Brilliant Marco 就像一个魅力! 1 最后一个问题对不起,在它提醒“空”的其他地方我不希望它重新加载页面..这是返回错误吗?或者有其他方法吗
  • 如果这是一个 asp:button 那么return false 应该阻止它,或者在你的标记中设置AutoPostBack=false
猜你喜欢
  • 1970-01-01
  • 2012-01-26
  • 2019-04-11
  • 2021-07-16
  • 1970-01-01
  • 2011-05-01
  • 2014-07-02
相关资源
最近更新 更多