0

I have a radio button and added jQuery validation to make sure this radio button is checked. This works fine.

html:

<form id="myform">
    <input type="radio" id="c1" name="cc" />
    <label for="c1"><span></span>Check Box 1</label>
    <input type="submit" />
</form>

javascript:

$(document).ready(function () {

    $('#myform').validate({ // initialize the plugin
        rules: {
            'cc': {
                required: true
            }
        },
        messages: {
            'cc': {
                required: "You must check this"
            }
        },
        submitHandler: function (form) {
            alert('valid form submitted');
            return false;
        }
    });

});

However if I add css to style the radio button, the validation doesn't work anymore. This is I guess, because the radiobutton is not displayed and thus the validation is removed from it. The question is of course, how can I fix this?

input[type="radio"] {
    display:none;
}
input[type="radio"] + label span {
    display:inline-block;
    width:19px;
    height:19px;
    margin:-1px 4px 0 0;
    vertical-align:middle;
    background:url(https://cdn.tutsplus.com/webdesign/uploads/legacy/tuts/391_checkboxes/check_radio_sheet.png) -38px top no-repeat;
    cursor:pointer;
}
input[type="radio"]:checked + label span {
    background:url(https://cdn.tutsplus.com/webdesign/uploads/legacy/tuts/391_checkboxes/check_radio_sheet.png) -57px top no-repeat;
}
Kat
  • 668
  • 2
  • 11
  • 24
  • possible duplicate of [jquery validator plugin with display:none form elements](http://stackoverflow.com/questions/12308138/jquery-validator-plugin-with-displaynone-form-elements) – Paul Roub Aug 21 '14 at 20:35
  • You are correct. That was fast. Thank you very much. I didn't think of looking into the link with the display:none elements. – Kat Aug 21 '14 at 20:41

1 Answers1

0

Paul Roub might be right, but there is another way around it. Setting display: none may let you style the radio button as you please, but it means that Screen Readers will never know about that radio button, and you are right that the validator will also not know about the button.

You could use a different CSS technique to hide the radio button while still making it work with screen readers and jQuery validator.

Try using these styles to hide the radio button (instead of display: none):

input[type="radio"] {
    border: 0;
    clip: rect(0 0 0 0);
    height: [height of element]
    margin: 0 [negative width of element] [negative height of element] 0;
    overflow: hidden;
    padding: 0;
    position: absolute;
    width: [width of element];
    opacity: 0.001;
}

The idea behind this fix is to use the clip() method to mask this element without affecting the position of anything else around. This was mostly borrowed from jQuery UI

Hope this helps.

grammar
  • 871
  • 10
  • 22