Image Radio Buttons

When using images to simulate a set of form radio buttons you still have to code in the radio buttons which are hidden using the css attribute display:none.
The script then swaps the image and the status of the relevant radio button.
The radio button value is still referenced as normal

1
2
3
4
5
 

<script type="text/javascript">
<!--
// Jeff
// www.huntingground.freeserve.co.uk

imgOn="selected.gif"
imgOff="unselected.gif" 

lastNum=0

function imgRad(num){

document.forms["img_rads"]["r1"][num].checked=true
document.images["p"+num].src=imgOn

if(lastNum != num){
document.images["p"+lastNum].src=imgOff
} 

lastNum = num

alert("Radio value = "+document.forms["img_rads"].elements["r1"][num].value)
}

//add  onload="imgRad(0)" to the opening body tag, the number is the default selected radio button

// -->
</script>


<form name="img_rads">

<div style="display:none">
<input type="radio" name="r1" value="1">
<input type="radio" name="r1" value="2">
<input type="radio" name="r1" value="3">
<input type="radio" name="r1" value="4">
<input type="radio" name="r1" value="5">
</div>

</form>

1 <img src="unselected.gif" name="p0" onclick="imgRad(0)">
2 <img src="unselected.gif" name="p1" onclick="imgRad(1)">
3 <img src="unselected.gif" name="p2" onclick="imgRad(2)">
4 <img src="unselected.gif" name="p3" onclick="imgRad(3)">
5 <img src="unselected.gif" name="p4" onclick="imgRad(4)">

The following example dynamically creates the images, assigns the onclick event to the image, and hides the radio buttons

 

<script type="text/javascript">
// Jeff
// www.huntingground.freeserve.co.uk

imgOff = "unselected.gif"
imgOn = "selected.gif"

lastNum=0

function initRads(n){ 

inputs = document.getElementById("raddiv").getElementsByTagName('input')

inputs[n].checked=true

for(var i=0; i<inputs.length; i++){ 

if(inputs[i].type == 'radio'){
newImg = document.createElement('IMG')
newImg.id = 'radImg'+i
newImg.style.marginBottom="5px"
newImg.i=i
newImg.onclick = function(){imgRad(this.i)}

if(inputs[i].checked){
newImg.src = imgOn
lastNum=i
}
else{
newImg.src = imgOff
}

inputs[i].parentNode.insertBefore(newImg, inputs[i])
inputs[i].style.display='none'
} 

}

imgRad(n)

} 

function imgRad(){

inputs[n].checked=true
document.getElementById('radImg'+n).src=imgOn

if(lastNum != n){
document.getElementById('radImg'+lastNum).src=imgOff
} 

lastNum = n

alert(inputs[n].value)
}

// add onload="initRads(0)" to the opening body tag, the number is the default selected radio button

</script>

<div id="raddiv">
<input type="radio" name="r1">
<input type="radio" name="r1">
<input type="radio" name="r1">
<input type="radio" name="r1">
<input type="radio" name="r1">
</div>