I've extended thecodeparadox's answer and added the essential functionality of a visible checked state. Here's the fiddle: http://jsfiddle.net/crowjonah/cfN5t
I restructured the inserted .after
, and borrowing heavily from this answer, added a .live
click function that will actually check and uncheck the hidden radio buttons, as well as give you the opportunity to change its appearance using CSS. I opted to use CSS background images rather than actual image tags with srcs stored in js variables, and added a .radio-image
class to each input that we'll use as our jQuery selector to target only the radio buttons we want to turn into images. Here's the HTML:
<label>How good?</label>
<input type="radio" class="radio-image" name="question1" id="best" value="5" />
<input type="radio" class="radio-image" name="question1" id="better" value="4" />
<input type="radio" class="radio-image" name="question1" id="average" value="3" />
<input type="radio" class="radio-image" name="question1" id="worse" value="2" />
<input type="radio" class="radio-image" name="question1" id="worst" value="1" />
The script:
$(function() {
$('input[type=radio].radio-image').each(function() {
var id = this.id;
$(this).hide().after('<a class="newrad" href="#"><div class="radio" id="' + id + '"></div></a>');
});
$('.newrad').live('click', function(e) {
e.preventDefault();
var $check = $(this).prev('input');
$('.newrad div').attr('class', 'radio');
$(this).find('div').addClass('checked');
$('input[type=radio].radio-image').attr('checked', false);
$check.attr('checked', true);
});
});
and the CSS (where we now define the images and optionally their checked states):
label {display:block;}
.radio {
opacity: 0.5;
width: 80px;
height: 80px;
float: left;
margin: 5px;
}
.checked {opacity: 1;}
#best {background: url(http://www.placehold.it/80&text=Best);}
#better {background: url(http://www.placehold.it/80&text=Better);}
#average {background: url(http://www.placehold.it/80&text=Average);}
#worse {background: url(http://www.placehold.it/80&text=Worse);}
#worst {background: url(http://www.placehold.it/80&text=Worst);}