jqueryjquery-validateerrorplacement

jquery Validate errorPlacement insert element + br + error


I'm trying to use 'errorPlacement' from jQuery Validation DOCS, like that:

$("#myform").validate({
    errorPlacement: function(error, element) {
        error.insertAfter(element);
    }
});

So far so good, but what I really want is to insert a <br /> tag between the input and the error label in each case:

<input>
**<br />**
<label class="error">

I have tried with:

error.insertAfter(element.append($('<br />'));

...but no luck. Is there a simple way of doing it? Any help is much appreciated.


Solution

  • You wouldn't need to do that.

    Just use the errorElement option to change the default error element from label (inline) to div (block), so that it automatically wraps to the next line.

    $("#myform").validate({
        errorElement: "div", // default is 'label'
        errorPlacement: function(error, element) {
            error.insertAfter(element);
        }
    });
    

    Otherwise, your code...

    error.insertAfter(element.append($('<br />'));
    

    Would be...

    error.insertAfter(element.append('<br />'));
    

    However, that still does not work as intended because append() is trying to put the content inside of element.


    This way works as you requested...

    $("#myform").validate({
        errorPlacement: function(error, element) {
            element.after(error).after('<br/>');
        }
    });
    

    DEMO: http://jsfiddle.net/1pfvug7r/