jquery验证消息显示在最后一个td上

时间:2017-02-06 10:13:54

标签: javascript jquery html html5

jQuery

rules:{
    gender: {
        required: true
    },
},
messages:{
    gender: {
        required: "Please specify your gender"
    },
},
errorPlacement: function (error, element) {
    if (element.attr("type") == "radio") {
        error.insertBefore(element.siblings('input[type="radio"][name="' + element.attr('name') + '"]:last'));
    } else {
        error.insertAfter(element);
    }
}

HTML

<table cellpadding="6" cellspacing="0">
    <tr>
        <td style="color:rgba(0,0,0,0.5); font-weight:300">Gender*</td>
        <td>
            <input type="radio" id="radio01" name="gender" value="male"/>Male
            <input type="radio" id="radio02" name="gender" value="female"/>Female
        </td>
    </tr>
</table>

我在单选按钮之间收到错误消息,破坏了我的整个布局!我需要它在第三个td中被撬开 例如:Gender .Male .Female "This field is required"

2 个答案:

答案 0 :(得分:0)

rules:{
   gender: {
       required: true
   },
},

messages:{
    gender: {
        required: "Please specify your gender"
    },
},
errorElement: 'span',
highlight: function (element, errorClass) {
    $('span.error').show();
}
<table cellpadding="6" cellspacing="0">
    <tr>
        <td style="color:rgba(0,0,0,0.5); font-weight:300">Gender*</td>
        <td>
            <input type="radio" id="radio01" name="gender" value="male"/>Male
            <input type="radio" id="radio02" name="gender" value="female"/>Female
        </td>
        <td>
            <span style="display:none"></span>
        </td>
    </tr>
</table>

可以使用此span元素,也可以添加类来高亮显示错误。

答案 1 :(得分:0)

您可以创建其他列以显示错误消息。

errorPlacement: function (error, element) {
    var html = "<td>" + error + "</td>";
    html.appendTo(element.parent());
}