开发者

jQuery radio validation - highlight all labels for radio

I'm using jQuery validation to validate a form with a radio button set on it (set = two radio buttons for this example). The radio buttons with labels are below. The form is on a jQueryUI dialog.

<input type="radio" name="chooseMe" value="开发者_C百科Yes" id="radio_yes" /><label for="radio_yes">Yes</label>
<input type="radio" name="chooseMe" value="No" id="radio_no" /><label for="radio_no">No</label>

I grabbed the highlight/unhighlight code from the validation plugin page on jquery.com http://docs.jquery.com/Plugins/Validation/validate

(go to the "Options" tab and search for "unhighlight")

highlight: function (element, errorClass, validClass) {
    $(element).addClass(errorClass).removeClass(validClass);
    $(element.form).find("label[for=" + element.id + "]").addClass(errorClass);
},
unhighlight: function (element, errorClass, validClass) {
    $(element).removeClass(errorClass).addClass(validClass);
    $(element.form).find("label[for=" + element.id + "]").removeClass(errorClass);
},

The first problem i'm having is when validated as required, only the "Yes" label is highlighted.

The second problem is if I don't resolve the validation issue and cancel out of the jQueryUI dialog, then come back into the dialog, the "Yes" label disappears completely.

To resolve the first issue, what i want to do is highlight both the "Yes" and "No" labels. So, working on the highlight code, i would need to get the name of the input ("chooseMe") from the element id, then from that name, for all the id's associated with that name ("radio_yes" and "radio_no"), highlight all the labels. Of course, then there's the converse for the unhighlight code.

Since i have several radio button sets in the form, i need this to be generic (no hardcoding "chooseMe", etc.)

Does that sound reasonable? If so, the only problem is i don't know how to do that :)

Thanks in advance.

jsFiddle as requested:

http://jsfiddle.net/Bd688/4/


Ok, this iteration of the jsfiddle highlights both labels:

http://jsfiddle.net/Bd688/6/

The idea is to get the name of the element and look for all the other elements of the same name, then apply the same code you were applying. So I just changed this:

$(element.form).find('[name='+element.name+']').each(function (i, sameName){
   $(element.form).find("label[for=" + sameName.id + "]").removeClass(errorClass); 
});

EDIT: Ok, so it turns out jQuery.validate doesn't really like you using its errorClass and applying it to labels. I made another class and it seems to be working:

http://jsfiddle.net/Bd688/7/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜