Casey Crookston Casey Crookston -4 years ago 112
CSS Question

Changing radio button to an image causes loss of jquery validation

I had a standard set of radio button inputs that used jQuery Validate. It all worked just fine:

<div class="panel-heading">1. What is your impression of ... <label class="error SurveyError" for="Impression"></label></div>
....
<div><label><input type="radio" class="SurveyQuestion" name="Impression" value="Excellent"> Excellent</label></div>
<div><label><input type="radio" class="SurveyQuestion" name="Impression" value="Good"> Good</label></div>
...


And then this script to add validation:

$('.SurveyQuestion').each(function () {
$(this).rules('add', {
required: true,
messages: {
required: "Please answer this question."
}
});
});


Worked great. But now, I need to style the radio button with an image. So the HTML changed to this:

...
<div><input type="radio" id="q1a" class="SurveyQuestion" name="Impression" value="Excellent"><label for="q1a"><span></span>Excellent</label></div>
<div><input type="radio" id="q1b" class="SurveyQuestion" name="Impression" value="Good"><label for="q1a"><span></span>Good</label></div>
...


With this CSS:

input[type="radio"] {
display:none;
}

input[type="radio"] + label span {
display:inline-block;
width:20px;
height:20px;
margin:-2px 10px 0 0;
vertical-align:middle;
background:url(/images/radio.png) no-repeat;
cursor:pointer;
}

input[type="radio"]:checked + label span {
background:url(/images/radio-selected.png) no-repeat;
}


Now, the styling looks great! But, the validation stopped working. Even with no answer, the form seems to think the question is valid... or... something.

I have noticed that if I leave the original checkbox visible...

input[type="radio"] {
/*display:none;*/
}


... that the validation still works. So, for some reason when using a fake checkbox made out of images instead of the real checkbox made by the browser, the validation stops working.

And, (kind of a different subject, but as long as we're here) I also noticed that with the imaged radio buttons, it's no longer possible to TAB into this question. Hitting the tab just skips right over all of these radio buttons.

Answer Source

You must be looking for-

input[type="radio"] {
    visibility: hidden;
}

to let them leave your document undisturbed-

input[type="radio"] {
    visibility: hidden;
    position: absolute;
    height: 0;
    width: 0;
}

Also to have them work in visibility hidden mode, wrap them in a label.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download