add an image to a html type input check box or radio

f1wade picture f1wade · Feb 25, 2011 · Viewed 27.7k times · Source

I'm trying to specify an image to be used for my unchecked and checked values for html input type checkbox and radio.

I have got this:

background: url("image.png") no-repeat;

but it doesnt seem to work on radio and checkbox only button.

Does anyone know something that will work?

Answer

f1wade picture f1wade · Mar 11, 2011

I have found and worked an answer. with help from these forums http://forums.digitalpoint.com/showthread.php?t=665980

all code is below: you can copy to a single file and add your own images and it will work.

<html>
<script type="text/javascript">
//global variables that can be used by ALL the function son this page.
var inputs;
var imgFalse = '52 0 ROff.png';
var imgTrue = '52 0 ROn.png';

//replace the checkbox with an image and setup events to handle it
function replaceChecks() {
    //get all the input fields on the page
    inputs = document.getElementsByTagName('input');

    //cycle trough the input fields
    for(var i=0; i<inputs.length; i++) {

    //check if the input is a checkbox
    if(inputs[i].getAttribute('type') == 'checkbox') {

        //create a new image
        var img = document.createElement('img');

        //check if the checkbox is checked
        if(inputs[i].checked) {
            img.src = imgTrue;
        } else {
            img.src = imgFalse;
        }

        //set image ID and onclick action
        img.id = 'checkImage'+i;
        //set image
        img.onclick = new Function('checkClick('+i+')');

        //place image in front of the checkbox
        inputs[i].parentNode.insertBefore(img, inputs[i]);

        //hide the checkbox
        inputs[i].style.display='none';
    }
}
}

//change the checkbox status and the replacement image
function checkClick(i) {
if(inputs[i].checked) {
    inputs[i].checked = '';
    document.getElementById('checkImage'+i).src=imgFalse;
} else {
    inputs[i].checked = 'checked';
    document.getElementById('checkImage'+i).src=imgTrue;
}
}

</script>
</html>
<body>
<input type="checkbox" />
<script type="text/javascript">replaceChecks();</script>
</body>