jquery Validate errorPlacement insert element + br + error

10,419

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/

Share:
10,419
andcl
Author by

andcl

Web developer

Updated on June 04, 2022

Comments

  • andcl
    andcl almost 2 years

    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.

  • andcl
    andcl over 9 years
    Thanks, but I need the errorElement to be the "label" because I want to validate some other inputs with that inline behaviour...
  • andcl
    andcl over 9 years
    Thanks @Sparky, I have tried the last approach, and it seems to work when I append some random text, i.e. error.insertAfter(element.append('random'));. However, when I put some HTML tag inside, nothing is appended... :(
  • Sparky
    Sparky over 9 years
    @andcl85, I don't think append() is the proper approach here as it puts content inside of the target. See: api.jquery.com/append
  • andcl
    andcl over 9 years
    Thank you very much @Sparky! That is exactly what I wanted!