Jquery验证错误放置(单选按钮)

时间:2011-04-13 04:05:48

标签: javascript jquery radio-button

我正在尝试使用Jquery验证插件来验证我的表单。我的大多数输入元素都出现了错误消息,但单选按钮只给我带来麻烦。

如果我没有为div.group类提供宽度,则错误消息会显示在整页的外部(因为我假设div宽度是页面的100%?)没有做任何事情会导致错误在第一个单选按钮而不是第二个单选按钮后显示的消息。我不能硬编码宽度,因为我想在几个宽度的无线电组上使用它。如何让它出现在单选按钮中单选按钮结束处的右边缘?

谢谢!

var validator = $("#myForm").validate({
        errorElement: "div",
        wrapper: "div",  // a wrapper around the error message
        errorPlacement: function(error, element) {

            if (element.parent().hasClass('group')){
                element = element.parent();
            }


            offset = element.offset();
            error.insertBefore(element)
            error.addClass('message');  // add a class to the wrapper
            error.css('position', 'absolute');
            error.css('left', offset.left + element.outerWidth());
            error.css('top', offset.top);
    }
});

然后

<p>
    <div class="group">
        <label>Gender</label>
        Male: <input id="gender_male" type="radio" name="gender" class="required" value="Male" />
        Female: <input id="gender_female" type="radio" name="gender" class="required" value="Female"  />
    </div>

也许只是在组中的最后一个单选按钮后出现错误消息的方法?如果我能得到最后一个元素的句柄,我可以相应地改变偏移量。

编辑:啊哈,我刚刚使用了div.group {display:inline-block;}。

4 个答案:

答案 0 :(得分:36)

您还可以使用此方法在特定字段的任何位置放置错误。

errorPlacement: function(error, element) {
  if (element.attr("name") == "PhoneFirst" || element.attr("name") == "PhoneMiddle" || element.attr("name") == "PhoneLast") {
     error.insertAfter("#requestorPhoneLast");
  } else {
     error.insertAfter(element);
  }
},

答案 1 :(得分:18)

甚至不需要JS errorPlacement来做...如果只是为单选按钮放置一个标签也是这样的:

<label class="label_radio" for="answer_A">
  <input id="answer_A" name="answers[question1].choiceArray" type="radio" value="A"/>Yes
</label>
<label class="label_radio" for="answer_B">
  <input id="answer_B" name="answers[question1].choiceArray" type="radio" value="B"/>No
</label>

<label for="answers[question1].choiceArray" class="error" style="display:none;">* Please pick an option above</label>

Jquery Validation插件会自动取消隐藏它并显示“必需”的消息。

答案 2 :(得分:2)

只需使用一些CSS:

#myform div.group label.error {float:right;padding-left:10px;}

答案 3 :(得分:1)

试试这个。它将错误放在引发错误的对象之前。如果您根据需要设置第一个单选按钮,这将起作用。为了保持一致性,我选择在所有输入类型上执行此操作,但您也可以稍微调整脚本以仅在无线电组验证失败时执行此操作。

$('form').validate({
  errorPlacement:
  function(error, element){
    var id=element[0]['id'];
    $( element ).before( "<label for='"+id+"' class='error'>"+error.text()+"</label>" );
  }
});