I would like to, instead of the standard radio button, use distinct images for each radio button. For the selected state I would like for a border to appear around the image.
I have tried making the images labels for the radio button and then hiding the button, but that seems to break the functionality for some reason.
I also have come across this article: http://ryanfait.com/resources/custom-checkboxes-and-radio-buttons/ which I could potentially somehow twist to my purposes.
Is there an easier/better way?
The alternatives to radio buttons are checkboxes and drop down boxes.
You can't have more than one button checked in the same radio group. You need to give the two sets different names.
Note that <input> tags only create the radio button element, not the label. To label a radio button, add a <label> element after the <input> element and insert a for attribute with the same value as the id of the associated <input> element. Then, write your label text in the <label> tag.
Yes, there is! This is an example of the simple ways:
No need for javascript
CSS
.radio_item{
display: none !important;
}
.label_item {
opacity: 0.1;
}
.radio_item:checked + label {
opacity: 1;
}
HTML
<!--RADIO 1-->
<input type="radio" class="radio_item" value="" name="item" id="radio1">
<label class="label_item" for="radio1"> <img src="img_url_here"> </label>
<!--RADIO 2-->
<input type="radio" class="radio_item" value="" name="item" id="radio2">
<label class="label_item" for="radio2"> <img src="img_url_here"> </label>
FIDDLE
- DEMO: http://so.lucafilosofi.com/is-there-an-easy-way-to-replace-radio-button-with-images-and-a-colored-border-fo/
jQuery
$('input:radio').hide().each(function() {
$(this).attr('data-radio-fx', this.name);
var label = $("label[for=" + '"' + this.id + '"' + "]").text();
$('<a ' + (label != '' ? 'title=" ' + label + ' "' : '' ) + ' data-radio-fx="'+this.name+'" class="radio-fx" href="#">'+
'<span class="radio' + (this.checked ? ' radio-checked' : '') + '"></span></a>').insertAfter(this);
});
$('a.radio-fx').on('click', function(e) {
e.preventDefault();
var unique = $(this).attr('data-radio-fx');
$("a[data-radio-fx='"+unique+"'] span").attr('class','radio');
$(":radio[data-radio-fx='"+unique+"']").attr('checked',false);
$(this).find('span').attr('class','radio-checked');
$(this).prev('input:radio').attr('checked',true);
}).on('keydown', function(e) {
if ((e.keyCode ? e.keyCode : e.which) == 32) {
$(this).trigger('click');
}
});
- full code in demo source;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With