1

I'm using the jQuery Validation Plugin and I would like to be able to dynamically determine the errorElement based on the type of element that has an error. I know that you can the errorElement like so:

$("form").validate({
    errorElement: "div"
});

However, I would like to be able to change it so that if the type were a checkbox or radio button, then I could make the errorElement an li. Does anyone know how to do this? Thanks!

1 Answer 1

9

I'm looking at the code in the plugin and the errorElement option is simply looking for an element as its parameter. Since there is no callback function for errorElement, I see no direct way to achieve what you ask without modifying the plugin itself.

Maybe you could do something with the errorPlacement callback instead.

Let's say just leave it as a label and then wrap it with some other container? Or use errorElement to put them all inside a <span>, while using errorPlacement to wrap them dynamically in whatever container. See jQuery .wrap().

    errorElement: 'span',
    errorPlacement: function (error, element) {
        var type = $(element).attr("type");
        if (type === "radio") {
            // custom placement
            error.insertAfter(element).wrap('<li/>');
        } else if (type === "checkbox") {
            // custom placement
            error.insertAfter(element).wrap('<li/>');
        } else {
            error.insertAfter(element).wrap('<div/>');
        }
    },

DEMO: http://jsfiddle.net/uLH4f/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.