Problem

Using the jQuery validation plugin, error message elements are dynamically injected into the DOM when a form field element is invalid. These elements can be formatted using CSS, but are on occasion not injected in the ideal location. This can be particularly bothersome when you’re working with other elements which are also dynamically inserted into the DOM.

Quick Solution

The jQuery validation plugin will place the error message text within the label for the invalid element with a class of error and a generated attribute. I have had good luck setting the value of generated attribute to true, but it may also work with a value of false. If you insert this element into the DOM yourself, where you’d like to to be, the plugin will use your element and not generate another.

<select id="agency" name="agency" class="required">
   <option value="">Please Select</option>
   <option value="FBI">FBI</option>
   <option value="NSA">NSA</option>
   <option value="Other">Other</option>
</select>
<input type="text" id="agencyOther" name="agencyOther" />
<label for="agency" class="error" generated="true" style="display: none;" />

Explanation

I think the quick solution above is fairly self explanatory. I may embellish on this later if I need a reminder of any other tricks related to this technique.

This entry was posted on March 25, 2013.