Jquery validation error message position for checkbox [duplicate]

冷暖自知 提交于 2019-12-25 18:08:06

问题


I am using jquery for checkbox validation(atleast one should be checked), here i need to display error message at the end of all checkboxes, but it always display after the label element and moves all checkboxes at the right side, which looks very weird. Below is my html code:

           <div>
            <label>Please Select a color:</label> 
                <input type="checkbox" id="color"  name="color" value="red"> red</input>
                <input type="checkbox" id="color"  name="color" value="green"> green</input>
                <input type="checkbox" id="color" name="color" value="yellow"> yellow</input>
                <input type="checkbox" id="color"  name="color" value="black"> black</input>
           </div>

Can anyone please tell me how to display error message at the right side after the end of all checkboxes without moving form structure.

Thanks in advance..

~Yash


回答1:


try this:

error.appendTo("div");

instead of this:

 error.appendTo( element.parent("div").next("div"));

Edit

<form id="myForm" method="post" name="myForm" action="">
        <div>
        <label>Please Select a color:</label> 
        <input type="checkbox" id="color"  name="color" value="red"> red</input>
        <input type="checkbox" id="color1"  name="color" value="green"> green</input>
        <input type="checkbox" id="color2" name="color" value="yellow"> yellow</input>
        <input type="checkbox" id="color3"  name="color" value="black"> black</input>
        <span id="errorToShow"></span> // Note this
        </div>
        <button type="submit">save</button>
    </form>

script:

$("#myForm").validate({
            rules: {
                color: "required"
            },
            messages: {
                color: "select atleast one color"
            },
            errorPlacement: function(error, element) {
                if (element.attr("name") == "color") {
                    error.appendTo("#errorToShow");
                } else {
                    error.insertAfter(element);
                }
            }
        });


来源:https://stackoverflow.com/questions/31134572/jquery-validation-error-message-position-for-checkbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!