occhiso occhiso - 1 month ago 13
HTML Question

Click on a div to toggle a checkbox inside of it using javascript

This seems to be a simple problem, but I dont use alot of javascript.

I have a div, with a checkbox in it, and would like the whole div to toggle the checkbox. This is what I have so far:

<div style="padding: 2em; border: 1px solid"
onClick="if (document.getElementById('cb').checked) document.getElementById('cb').checked=false; else document.getElementById('cb').checked=true;">
<input name="cb" id="cb" type="checkbox">
</div>


Only problem is when you click the actual checkbox, it get toggled twice, and therefore doesn't change.

Any ideas?

Answer

It's possible you could implement this is a more robust and accessible way by using the label element to wrap the area you want clickable. eg.

<label for="cb">
    <div style="padding: 2em; border: 1px solid">
        <input name="cb" id="cb" type="checkbox">
    </div>
</label>

I haven't tested the above code, but I believe all browsers support clicking of labels to check an input box.