usual but I need to have different custom radio button images per button.
So Radio1 would have different images to Radio2.
Trying it out on the code below but it won’t work so I must be doing something wrong?
Here’s the code:
<label for="radio1">
<img src="radio1_unchecked.png" style="vertical-align:middle" />
<input name="radiogroup" type="radio" id="radio1" style="display:none;">
</label>
<label for="radio2">
<img src="radio2_unchecked.png" style="vertical-align:middle" />
<input name="radiogroup" type="radio" id="radio2" style="display:none;">
</label>
<script>
$(document).ready(function(){
var radio1checkedImage = "radio1_checked.png",
radio1uncheckedImage = "radio1_unchecked.png",
radio2checkedImage = "radio2_checked.png",
radio2uncheckedImage = "radio2_unchecked.png";
$('img').attr("src", radio1uncheckedImage);
$('#radio1, #radio2').change(function() {
var r;
r = $("#radio1");
r.prev().attr("src", r[0].checked ? radio1checkedImage : radio1uncheckedImage);
r = $("#radio2");
r.prev().attr("src", r[0].checked ? radio2checkedImage : radio2uncheckedImage);
});
});
</script>
Update: Here is the same code as above but without the multiple images.
As you can see it works. Can’t the code be modified to have multiple images per radio?
In addition my other answer, which uses CSS, let me offer an alternative solution.
Firstly; you want to keep track of which image goes with which radio button. Why not use an object literal?
This way you can easily refer to the different URL’s like, e.g.:
checkedImages['radio2'].The change event handler would look very similar. The only difference is what you do with the
checkedLabelsand theuncheckedLabels:The main differences:
children()to find the images.each()to add more complicated logic for each of the unchecked label.<label>sforattribute (using.attr('for')) to find out which image we should apply.In this example only the
checkedstate has different images for the different radio’s. If you need differentuncheckedimages as well, you can easily apply the same principle.Live example: http://jsbin.com/acalir/edit#javascript,html,live
P.S. don’t forget to set the
srcto the unchecked images (in HTML), or do the following (in JS):This fires the
changeevent programmatically, which will cause the unchecked images to be applied.