I am using JQuery and custom images for custom radio buttons. Right now, it would work as a checkbox. I need it to work as a radio.
When I click on either of both radio’s both will get ticked instead of one at a time. Am I missing something?
HTML:
<label for="radio1">
<img src="radio_unchecked.png" style="vertical-align:middle" />
<input name="radiogroup" type="radio" id="radio1" style="display:none;">
</label>
<label for="radio2">
<img src="radio_unchecked.png" style="vertical-align:middle" />
<input name="radiogroup" type="radio" id="radio2" style="display:none;">
</label>
JavaScript:
$(document).ready(function() {
$("#radio1").change(function() {
if (this.checked) {
$(this).prev().attr("src", "radio_checked.png");
} else {
$(this).prev().attr("src", "radio_unchecked.png");
}
});
$("#radio2").change(function() {
if (this.checked) {
$(this).prev().attr("src", "radio_checked.png");
} else {
$(this).prev().attr("src", "radio_unchecked.png");
}
});
});
The radio buttons are working correctly (proof), but your logic for updating the images is incorrect. Both images have to change when either radio button is clicked, since both values change (and the
changehandler is only fired on the one that you clicked). Have a singlechangehandler used by both radio buttons, and set both images on every change, e.g.:Live example
Side note: If your target browsers support the
:checkedpseudo-class (IE only has this as of IE9, not in IE8 or earlier) and adjacent sibling combinator from CSS3, you can do this entirely with CSS:HTML:
CSS:
Live example
Or alternately (it’s just the selectors that are different):