JAVAGeek
JAVAGeek

Reputation: 2794

jQuery validation on radio button

I have two radio buttons in my form for gender selection.

I am using this plugin for validation. When I apply validation on radio button, this plugin places the error label between the two radio buttons.

here is the fiddle: http://jsfiddle.net/wyFQp/1/

HTML:

<head>
    <body>
        <form id='registration_form'>
            <input type="radio" value="M" name="gender" class="gender" id="genderm"
            />Male
            <input type="radio" value="F" name="gender" class="gender ml_10" id="genderf"
             />Female
            <input type='submit' />
        </form>
    </body>

How can I place the error label after both radio buttons? Or at least on some decent place?

Upvotes: 1

Views: 2809

Answers (1)

Fabr&#237;cio Matt&#233;
Fabr&#237;cio Matt&#233;

Reputation: 70129

Add an error label in your markup where you'd like the error to show:

<label class="error" generated="true" for="gender" style="display:none;"></label>

Fiddle

When associating it with radio inputs, the error label's for attribute corresponds to radios' name - this facilitates things as radios with the same name will only have one radio selected at a time and one error label associated with the group.
For text inputs (and select/textarea/type="checkbox") though, the id must be used.


Another less hackish way is to use the errorPlacement option with an error container, e.g.:

<div id="genderErrorContainer"></div>
$("#registration_form").validate({
    rules: {[...]},
    messages: {[...]},
    submitHandler: fn,
    errorPlacement: function(error, element) {
        if (element.prop('name') === 'gender') {
            error.appendTo('#genderErrorContainer');
        }
    }
});

Updated fiddle

Of course, you can also use other DOM manipulation methods to add the error element to the DOM, for example .append, .prepend, .after, insertAfter, .before, .insertBefore combined with DOM traversal based on the element that originated the validation error, which may not require extra markup depending on your HTML structure.

Upvotes: 4

Related Questions