Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 583
occhiso Avatar asked Feb 25 '09 00:02

occhiso


People also ask

Can you give a Div an onclick?

To set an onClick listener on a div element in React:Set the onClick prop on the div. The function you pass to the prop will get called every time the div is clicked. You can access the div as event. currentTarget .

Can we use Onclick for checkbox?

The CheckBox has been assigned a JavaScript OnClick event handler. When the CheckBox is clicked, the ShowHideDiv JavaScript function is executed. Inside this function, based on whether CheckBox is checked (selected) or unchecked (unselected), the HTML DIV with TextBox is shown or hidden.


2 Answers

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

For example:

<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.

like image 156
Andy Hume Avatar answered Oct 24 '22 07:10

Andy Hume


onclick="if (event.target.tagName != 'INPUT') document.getElementById('cb').checked = !document.getElementById('cb').checked"
like image 43
Alex Barrett Avatar answered Oct 24 '22 07:10

Alex Barrett