7

我使用Jquery 验证插件来验证下面的这两个输入元素。当输入无效时,插件会在输入字段后立即生成一个标签标签,例如:<label for="company" style="">Required !</label>

问题:如何将错误消息放入现有<span class="help-inline">而不是生成新的<label>

非常感谢您提前提供的帮助。

<script type="text/javascript">

 $('#signUpForm').validate({
                            debug: false,
                            rules: {company:"required",username:"required"},
                         messages: {company:"Required !",username:"Required !"}
                          })// End of validate()

</script>


<div class="control-group">
   <label class="control-label" for="company">Company Name</label>
   <div class="controls">
      <input type="text" name="company">
      <label for="company">Required !</label> // -> this line is generated by Plug-In.
      <span class="help-inline">(required)</span>
   </div>
</div>

<div class="control-group">
   <label class="control-label" for="username">User Name</label>
   <div class="controls">
      <input type="text" name="username">
      <span class="help-inline">(required)</span>
   </div>
</div>
4

1 回答 1

19

利用内置选项并让插件创建您的span元素会更容易。生成的 HTML 的最终结果将是您所要求的。

  • 用于errorElement将 更改<label><span>.

  • 用于errorClass将默认错误类更改为help-inline

jQuery :

$(document).ready(function () {

    $('#signUpForm').validate({ // initialize the plugin
        errorElement: 'span',
        errorClass: 'help-inline',
        rules: {
            company: "required",
            username: "required"
        },
        messages: {
            company: "Required !",
            username: "Required !"
        }
    });

});

HTML

<form id="signUpForm">
    <div class="control-group">
        <label class="control-label" for="inputCompanyName">Company Name</label>
        <div class="controls">
            <input name="company" type="text" id="inputCompanyName" placeholder="" />
        </div>
    </div>
    <div class="control-group">
        <label class="control-label" for="inputFirst">User Name</label>
        <div class="controls">
            <input name="username" type="text" id="username" placeholder="" />
        </div>
    </div>
    <input type="submit" />
</form>

演示:http: //jsfiddle.net/eRZFp/

顺便说一句:您的User Name字段缺少name属性name="username". 为了让这个插件正常工作,所有输入元素都必须包含一个唯一的name属性。

于 2013-06-10T17:37:41.663 回答