views:

619

answers:

4

Using the jQuery Validation plug-in for the following form:

<form id="information" method="post" action="#">

            <fieldset>
                <legend>Please enter your contact details</legend>
                <span id="invalid-name"></span>
                <div id="id">
                    <label for="name">Name: (*)</label>
                    <input type="text" id="name" class="details" name="name" maxlength="50" />
                </div>

                <span id="invalid-email"></span>
                <div id="id">
                    <label for="email">Email: (*)</label>
                    <input type="text" id="email" class="details" name="email" maxlength="50" />
                </div>
            </fieldset>
            <fieldset>
                <legend>Write your question here (*)</legend>
                <span id="invalid-text"></span>
                <textarea  id="text" name="text" rows="8" cols="8"></textarea>


            <div id="submission">
                <input type="submit" id="submit" value="Send" name="send"/>
            </div>
            <p class="required">(*) Required</p>
            </fieldset>

             </form>

How can I place the errors inside the span tags? (#invalid-name, #invalid-email, #invalid-text)

I read the documentation about error placement but I did not get how it works. Is it possible to handle each single error and place it in the specified element?

Thank you

+1  A: 

This is a basic structure, you can use whatever selector you would like in the method. You have the error element and the element that was invalid.

jQuery.validator.setDefaults({
    errorPlacement: function(error, element) {
        error.AppendTo(element.prev());
    }
});

Or to target the ID, you could do

jQuery.validator.setDefaults({
    errorPlacement: function(error, element) {
        error.AppendTo('#invalid-' + element.attr('id'));
    }
});

Not tested, but should work.

Dustin Laine
Actually, It does not work but it helped me to understand how it works in general!
Mirko
You should post working code to help others.
Dustin Laine
A: 

I found the using .insertAfter rather than .appendTo works.

jQuery.validator.setDefaults({
    errorPlacement: function(error, element) {
        error.inertsAfter('#invalid-' + element.attr('id'));
    }
});
Thanks, I will give it a try!
Mirko
A: 
Stefan Morrow