Position error message with jQuery Validate

前端 未结 2 1971
南方客
南方客 2020-12-12 06:16

I have the following HTML. The label is inserted by the jQuery validation plugin, and I don\'t think I could position it anywhere but directly following the input. I could

相关标签:
2条回答
  • 2020-12-12 06:28

    Don't use CSS when you could just create the proper DOM markup in the first place.

    Use the errorPlacement option that is provided by the jQuery Validate plugin to override the default message placement.

    $('#myform').validate({
        // other options,
        errorPlacement: function(error, element) {
            error.insertAfter(element); // <- default, change this to whatever you need
        }
    });
    

    Quote OP:

    "I could easily add a tag around the "Invite Contact" if necessary."

    I surrounded your "Invite Contact" text with <span> tags and used this function in the demo...

    errorPlacement: function (error, element) {
        error.insertAfter($(element).next());
    }
    

    Working DEMO: http://jsfiddle.net/8pawpsht/


    Can be restricted to a certain element by using a conditional...

    errorPlacement: function (error, element) {
        if ($(element).attr('id') == 'foo') {
            error.insertAfter($(element).next());
        } else {
            error.insertAfter(element); // <- default
        }
    }
    

    DEMO 2: http://jsfiddle.net/8pawpsht/1/ or http://jsfiddle.net/8pawpsht/2/

    0 讨论(0)
  • 2020-12-12 06:42

    You could float the checkbox right, and the label left. You could add a div inside of invite, to control this.

    HTML

    <p id="invite">
    <span class="wrapper">
    <input type="checkbox" checked="" value="1" name="invite" class="error">
    <label id="invite-error" class="error" for="invite">Email is required if you wish to invite.</label>
    </span>
    <strong>Invite Contact</strong>
    </p>
    

    CSS

    #invite {
    display:block;
    width:100%;
    height:250px;
    background:#d7d7d7;
    margin:0 auto;
    text-align:center;
    }
    .wrapper {
    background:white;
    display:block;
    border:2px solid #333;
    height:20px;
    width: 275px;
    margin:0 auto;
    }
    .error {
    float:right;
    }
    #invite-error {
    float:left;
    }
    

    For reference, check out my codepen here

    0 讨论(0)
提交回复
热议问题