【问题标题】:Why isn't the jquery validate plugin validating my checkbox?为什么 jquery validate 插件不验证我的复选框?
【发布时间】:2012-03-26 05:43:34
【问题描述】:

此代码是从另一个文件复制的,它在该文件中工作,我检查了变量和表单 id,我确定名称与 js 代码一致。 genFrom 中的文本框也验证工作,只有复选框不工作。

<script src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script>
$(document).ready(function(){
    $("#genForm").validate();
    $("#genForm").validate( {
        rules: {
            agree: {
                required: true
            }
        }
    })
});
</script>
<form id="genForm"  method="post" action="verify.php">
<div class="container">
    <div class="hero-unit">
        <h1>Subscribe for final</h1>
    </div>
    <div class="clearfix">
        <label>Email</label>
        <div class="input">
            <input name="Email" type="text" class='required'>
        </div>
    </div>
    <br>
    <br>
    <div class="clearfix">
    <label>Agreements:</label>
        <div class="input"> 
        <ul class="inputs-list">
            <li>                                      
            I accept the terms and conditions.
            <!-- Check box is here, not working -->
            <input type="checkbox" name="agree" value="1">
            </li>
        </ul>
        </div> 
    </div> 
    <br>
    <input class="btn primary" type="submit" value="Submit">
</form>

【问题讨论】:

    标签: jquery jquery-plugins jquery-validate


    【解决方案1】:

    由于某种原因,您在同一个表单上调用了两次validate(),您只需要一次:

    // $("#genForm").validate(); No need for this
    
    $("#genForm").validate( {
      rules: {
          agree: {
              required: true
          }
       }
    });
    

    演示:http://jsfiddle.net/8MV5F/

    在没有参数的情况下调用validate() 确实有一些(可配置的)默认行为,其中之一是将required 规则附加到带有class='required' 的元素,这就是电子邮件字段起作用的原因。您还可以为此使用required 属性,此外,您还可以使用type="email" 来验证电子邮件地址,而无需在您的规则中指定它。

    这是一个简单的例子:http://jsfiddle.net/8MV5F/2/

    <form id="genForm"  method="post" action="verify.php">
        <label>Email:<input name="Email" type="email" required></label>          
        <label>I accept the terms and conditions.
        <input type="checkbox" name="agree" value="1" required></label>
        <input class="btn primary" type="submit" value="Submit">
    </form>
    
    $("#genForm").validate();
    

    如果支持,这具有回退到本机浏览器验证的优势,以防 javascript 被禁用,甚至只是被破坏。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多