Ok, I have a label, inside this label is a div, which contains an image, and some text. The div has an onClick call to a javascript function, that changes the color of the div inside the label, and also checks the checkbox (for some reason, IE and firefox didn’t want to check it correctly, chrome worked fine).
Javascript:
<script language="javascript" type="text/javascript">
function changecolor(id, chck1, firstcolor, secondcolor)
{
divid = document.getElementById(id);
chkboxid = document.getElementById(chck1);
if(chkboxid.checked){
divid.style.background= firstcolor;
var ua = navigator.userAgent.toLowerCase();
if (ua.indexOf('safari/') == -1){
chkboxid.checked = false ;
}
}
else{
divid.style.background= secondcolor;
var ua = navigator.userAgent.toLowerCase();
if (ua.indexOf('safari/') == -1){
chkboxid.checked = true ;
}
}
}
html:
<input type="checkbox" id="idbox" name="cboxwithlabel" value="Another check box"><label for="idbox"><div class="listing" onClick="changecolor('Test33', 'idbox', '#09C', '#0F0');" id="Test33">Another checkbox<img src="images/checkmark.png" height="80" width="80" /></div></label>
Ok, so using this works fine in Firefox, and Chrome, but IE 7 (haven’t tested other versions yet), it will only check the checkbox if you click the image inside the div. Clicking the div itself, only changes the background color. So what is the fix to have IE work so that when you click the div it also checks the checkbox?
One of the nice things that browsers do, is triggering click events from
<label>elements for us.So my recommendation is to attach the click handler to the checkbox itself. This way your function becomes MUCH simpler.
Also, it’s illegal to put block-level elements inside of line-level elements, so I’ve changed your
<div>to a<span>and used CSS to make it render as a block-level element.