2

I have an input and a label in a div like so:

<div class="dropdown-item">
  <input id="inputId" name="filtercheckbox" type="checkbox" />
  <label for="inputId">Basic Label</label>
</div>

I want the input checkbox to check/uncheck when the div, label or input is clicked.

I have tried making the label width and height 100% which does not expand to cover the whole div.

I have also tried the solution from this question: change checkbox status (true/ false) on div click

However while clicking the div now toggles the input, clicking the label does not. The JSFiddle with the above implemented solution is here: http://jsfiddle.net/qk1dg79e/1/ This is the closest I have come to the solution.

I am using bootstrap so changing the display property on the div is not an option.

How can I make it so that when the div, label or input is clicked it toggles the input?

2 Answers2

2

The simplest solution here is to replace div element with the label element, like below.

HTML:

<label for="inputId1" class="label">
  <input id="inputId1" name="filtercheckbox" type="checkbox" />Basic Label
</label>

CSS

.label {
  border: 1px solid red;
  border-radius: 4px;
  width: 100%;
  padding: 10px;
  display: block;
  box-sizing: border-box;
}
Andrei Todorut
  • 4,260
  • 2
  • 17
  • 28
0

You can add a mouse-down event listener to the wrapper elements and check if you clicked on the correct element e.g. the wrapper itself, before inverting the checkbox state.

If you click in the red area, it will detect it and invert the state of the checkbox.

addToggleListenerToCheckboxWrapper('.dropdown-item'); // Add listener(s)

/**
 * Adds a checkbox toggle listener to the wrapping div.
 * 
 * @param {string|Element|NodeList} wrapper - Elements to add listener to.
 */
function addToggleListenerToCheckboxWrapper(wrapper) {
  if (typeof wrapper === 'string') wrapper = document.querySelector(wrapper);
  NodeList.prototype.isPrototypeOf(wrapper)
    ? Array.from(wrapper).forEach(__addToggleListenerToCheckboxWrapper)
    : __addToggleListenerToCheckboxWrapper(arguments[0]);
}

/**
 * @private
 */
function __addToggleListenerToCheckboxWrapper(wrapperElement) {
  wrapperElement.addEventListener('mousedown', function(e) {
    if (e.target === wrapperElement) {
      let checkbox = e.target.querySelector('input[type="checkbox"]');
      checkbox.checked = !checkbox.checked; // invert
    }
  }, false);
}
.dropdown-item {
  background: red;
}
<div class="dropdown-item">
  <input id="inputId" name="filtercheckbox" type="checkbox" />
  <label for="inputId">Basic Label</label>
</div>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132