JQuery validation, put an error message in an existing element instead of generating the <label> tag

I am using the jQuery validation plugin to validate these two input elements below. If the input is invalid, the plug-in will generate a tag tag immediately after the input field, for example: <label for="company" style="">Required !</label>

Question: How to put an error message in an existing <span class="help-inline"> instead of generating a new <label> ?

Thanks so much for your help in advance.

 <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> 
+6
source share
1 answer

It would be easier to use the built-in options and let the plugin create your span elements. The end result of the generated HTML will be what you request.

  • Use errorElement to change <label> to <span> .

  • Use errorClass to change the default error class to 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> 

DEMO: http://jsfiddle.net/eRZFp/

BTW . The User Name field is missing the attribute name , name="username" . For this plugin to work correctly, all input elements must contain a unique name attribute.

+13
source

Source: https://habr.com/ru/post/946979/


All Articles