PeraMika
PeraMika

Reputation: 3688

Need to put HTML within the error label container of jQuery Validate plugin

I have a simple validation for my input elements:

$("#forma").validate({
    errorClass: "red"
});
$("#input").each(function(index, elem) {
    var rules = {
        required:true
    };
    $(elem).rules("add", rules);
});   

So, when error occurs - error messages are displayed and those error messages are inside label elements. For example, if you forget to enter the last name and you click submit button - this label element will be added:

<label id="lastname-error" class="red" for="lastname">This field is required.</label>

Now, I would like to add empty span element inside of those labels, at the beginning (prependTo) with the background-image and other CSS properties, so it will look like this:

<label id="lastname-error" class="red" for="lastname"><span class="myspan"></span><This field is required.</label>    

I guess that this can be done by some event, like: when an error occurs - execute this:

var html = "<span></span>";
$(html).css({
    "background-image": "url('../images/arrowRight.png')",
    "padding-right": "26px",
    "background-repeat: no-repeat"
}).prependTo("label.red");    

Do you know how can I do this?

Upvotes: 0

Views: 3352

Answers (1)

Sparky
Sparky

Reputation: 98738

Desired output:

<label id="lastname-error" class="red" for="lastname"><span class="myspan"></span><This field is required.</label>

"I guess that this can be done by some event"

No, you would not need to use a custom event or function. You would simply use the plugin's errorPlacement option to construct your custom HTML.

The default code is error.insertAfter(element), so this just needs to be modified. You take the text of the error message and prepend it with your <span>, then replace the content of the default error label with your new HTML.

$("#forma").validate({
    // your rules & options,
    errorClass: "red",
    errorPlacement: function(error, element) {
        var html = '<span class="myspan"></span>' + $(error).text();
        $(error).html(html).insertAfter(element);
    }
});

DEMO: http://jsfiddle.net/zrekogqd/

Inspecting the DOM of the jsFiddle shows this result...

<label id="lastname-error" class="red" for="lastname">
    <span class="myspan"></span>This field is required.
</label>

Upvotes: 2

Related Questions