jQuery Validation插件errorPlacement for checkbox

我使用jQuery Validation插件来validation我的表单。 我的问题是复选框的错误消息的位置。 请看这个图像:

在此处输入图像描述

这是与复选框+ jQueryvalidation相关的html部分:

.checkbox-grid li { display: block; float: left; width: 25%; }
  • //Continued the same for OTHER CHECKBOXES
//html for other questions... $(document).ready(function() { $('#form2').validate({ // initialize the plugin errorLabelContainer: "#messageBox", wrapper: "li", rules: { "q8[]": { required: true, }, "q9[]": { required: true, }, q10: { required: true, }, q11: { required: true, }, q12: { required: true, } }, errorPlacement: function(error, element) { if (element.attr("type") == "radio") { error.insertBefore(element); } else { error.insertBefore(element); } } }); });

如果可以解决此问题或在问题旁边显示错误消息(对于所有输入类型),有人可以帮助我吗? (我的意思是与问题完全相同的行,在*之后)

谢谢

我为你的问题在label添加了一个class ,以便更容易找到…

  

然后你只需要练习你的“DOM遍历”技术。 研究这里的方法。

  • $(element).parents('div')找到elementdiv容器。

  • 然后.prev($('.question'))将你带到.question ,这是这个div的第一个兄弟。

把它们放在一起,它会在问题后面插入错误信息。

 error.insertAfter($(element).parents('div').prev($('.question'))) 

errorPlacement

 errorPlacement: function (error, element) { if (element.attr("type") == "checkbox") { error.insertAfter($(element).parents('div').prev($('.question'))); } else { // something else if it's not a checkbox } } 

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

也许您不需要条件,因为该技术应该适用于所有input类型。

 errorPlacement: function (error, element) { error.insertAfter($(element).parents('div').prev($('.question'))); } 

否则,如果您的HTML不同,那么您可以使用带有略微修改的DOM遍历的条件。