20

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?

occhiso
  • 3,161
  • 4
  • 22
  • 16

7 Answers7

42

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.

Andy Hume
  • 40,474
  • 10
  • 47
  • 58
  • Im fairly new to web stuff, and I've actually never used – occhiso Feb 25 '09 at 00:38
  • 1
    I just read a related article which explains it here: http://stackoverflow.com/questions/2123/how-do-i-make-a-checkbox-toggle-from-clicking-on-the-text-label-as-well Thanks, I think I'll experiment with this. – occhiso Feb 25 '09 at 00:40
  • You can even put the style attributes into the label element itself and trash the div altogether. – Zack The Human Feb 25 '09 at 00:47
  • I cant seem to get the label to span across the whole
    , it only spans across the actual label of the checkbox. I actually intend to have an image inside of the div as well as the checkbox, but cant get the label to cover all of this. Thanks anyway, that would have been cleaner.
    – occhiso Feb 25 '09 at 00:47
  • AH, did it, will post a small example soon :) Thanks to all – occhiso Feb 25 '09 at 00:49
  • 2
    I needed display: block; and replaced the div with the label: – occhiso Feb 25 '09 at 00:59
  • This worked perfectly for me, just a note: The `for="cb"` inside label references the input `id`. In my case I populated the check boxes dynamically using an incremented int for `for` and `id`: `for='cb".$i."'` and `id='cb".$i."'` – jnthnjns Jan 29 '13 at 17:15
7
onclick="if (event.target.tagName != 'INPUT') document.getElementById('cb').checked = !document.getElementById('cb').checked"
Alex Barrett
  • 16,175
  • 3
  • 52
  • 51
  • Thanks, I knew it would something simple like that! I did a similar thing, but stuffed it up :) – occhiso Feb 25 '09 at 00:21
  • 1
    I know this is year late, but I think this is the best answer since it covers more situations. If you wanted to make a `` element clickable the `label` method wouldn't work, whereas this certainly does. – Stuart Clarke Feb 23 '18 at 09:44
  • Of course always try to avoid inline code but thank you! This was very useful! – Lucho Bellofatto Dec 22 '22 at 21:42
3

Based on some of the previous answers, this is what worked best for me with html like this:

<div class="option_item">
  <input type="checkbox" value="1" checked="checked">
</div>

jQuery like this:

$.fn.toggleCheckbox = function() {
  this.attr('checked', !this.attr('checked'));
}

$(document).ready(function(){
  $(".option_item").click(function (e) {    
    if (e.target.tagName != 'INPUT') {
      $(this).find("input").toggleCheckbox();
      return false;
    }
  });
);
Tom Kirkpatrick
  • 131
  • 1
  • 3
1

The root of the problem is that when you click on the checkbox, the click event is propagated up the DOM to parent elements.

So the checkbox handles the click event by toggling itself, and then the DIV receives the click event and toggles the checkbox again.

The simplest solution would be to stop propagation of the event, by adding this to the input element:

onClick="event.stopPropagation();"

While this is defined in the W3C DOM Level 2 Event Model, it may not be supported in all browsers so you may want to use a cross-browser library like Prototype or jQuery to ensure compatibility.

user59200
  • 384
  • 2
  • 2
0

Here is my implementation of checkbox for div

Link:https://codepen.io/ashwinshenoy/pen/oYXqMV

       <div id="checkboxes">
            <input type="checkbox" name="rGroup" class="check_cat" value="Adventure Sports" id="r1"/>
            <div class="check_overlay">
                <i class="fa fa-check-circle"></i>
            </div>
            <label class="whatever" for="r1">
                <img src="http://i.imgur.com/SfQVTlR.png" class=" img-responsive width100" />
                <div class="row">
                    <div class="col-xs-offset-3 col-xs-3">
                        <div class="check_details">
                            <i class="fa fa-user"><span> 500</span></i>
                        </div><!--check_details end-->
                    </div><!--col-xs-* end-->
                    <div class="col-xs-3">
                        <div class="check_details">
                            <i class="fa fa-bitbucket"><span> 500</span></i>
                        </div><!--check_details end-->
                    </div><!--col-xs-* end-->
                </div><!--inner row end-->
            </label>
            <br>
            <div class="check_name_div">
                Adventure Sports
            </div>
        </div><!--checkboxes end-->

CSS and JS in codepen updated

Ashwin
  • 562
  • 6
  • 14
0

look into using jQuery rather than programming against the dom yourself. using a library like jQuery means your code is more likely to work on most browsers

http://docs.jquery.com/Effects/toggle

Damien McGivern
  • 3,954
  • 3
  • 27
  • 21
0

Try,

.switch_ {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.switch_ input { 
  opacity: 0;
  width: 0;
  height: 0;
}

.switch_slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ff2626;
  -webkit-transition: .4s;
  transition: .4s;
}

.switch_slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked + .switch_slider {
  background-color: #12e4a0;
}

input:focus + .switch_slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked + .switch_slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}

/* Rounded sliders */
.switch_slider.round {
  border-radius: 34px;
}

.switch_slider.round:before {
  border-radius: 50%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div align="center"><label class="switch_">
  <input type="checkbox" id="size_act">
  <span class="switch_slider round"></span>
</label> 
</div>
<div align="center" onClick="$('#size_act').click();">Inactive / Active</div>
Waruna Manjula
  • 3,067
  • 1
  • 34
  • 33