jquery Validate errorPlacement insert element + br + error

andcl picture andcl · Dec 11, 2014 · Viewed 10.5k times · Source

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.

Answer

Sparky picture Sparky · Dec 11, 2014

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 />'));
  • is missing a closing parentheses, )
  • is not the correct format... you do not put a string to append within a jQuery selector, $()

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/