在Jquery中复选框和标签之间显示验证错误

时间:2016-09-13 09:31:19

标签: jquery html css jquery-validate

我在jquery validation中遇到了一些问题。错误显示在复选框和标签之间。我必须在下面显示错误。你能帮帮我吗?

HTML

<input type="checkbox" name="standard_subject[]"  value="IX" ><span class="checkboxtext">IX</span>
<input type="checkbox" name="standard_subject[]" value="X" ><span class="checkboxtext ">X</span>
<input type="checkbox" name="standard_subject[]" value="Maths"><span class="checkboxtext">Maths</span>
<input type="checkbox" name="standard_subject[]" value="Science"><span class="checkboxtext">Science</span>
<input type="submit" value="Download now"  name="submit" > 

enter image description here

1 个答案:

答案 0 :(得分:0)

请使用jquery验证js的“errorPlacement”事件来放置错误。请查看以下代码段以获得更多理解。

$('form').validate({
  rules: {
    "standard_subject[]": { 
      required: true, 
      minlength: 1 
    } 
  },
  messages: {
    "standard_subject[]": "Please select standard."
  },
  errorPlacement: function(label, element) {
    label.addClass('errorMsq');
    element.parent().append(label);
  },
});
$('button').click(function () {
  $('form').valid();
});
.errorMsq {
  color: red;
  display: block;
}
<form>
  <div>
    <input type="checkbox" name="standard_subject[]"  value="IX" ><span class="checkboxtext">IX</span>
    <input type="checkbox" name="standard_subject[]" value="X" ><span class="checkboxtext ">X</span>
    <input type="checkbox" name="standard_subject[]" value="Maths"><span class="checkboxtext">Maths</span>
    <input type="checkbox" name="standard_subject[]" value="Science"><span class="checkboxtext">Science</span>
  </div>
  <br>
  <input type="submit" value="Download now"  name="submit" > 
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.min.js"></script>