简体   繁体   中英

How to make a whole li element clickable to toggle checkmark?

I have a list where each line has name on the left and a checkmark on the right, I want to be able to just click on the whole element to toggle the checkbox without using jquery.

<div class="list-checkbox list-group list-button mx-auto mt-2">
  <button class="list-group-item d-flex justify-content-between align-items-center">
    <span>Option 1</span>
      <label class="checkboxCustom my-auto">
      <input type="checkbox" checked="checked">
      <span class="checkmark"></span>
      </label>
   </button>
 </div>

This is my script

  document.getElementbyClassName('div.list-checkbox button').click(function() {
    var $cb = $(this).find(":checkbox");
    if (!$cb.getAttribute("checked")) {
      $cb.setAttribute("checked", true);
    } else {
      $cb.setAttribute("checked", false);
    }
  });

it seems like you are using JQuery so I just added some small changes:

  $('div.list-checkbox').on('click',function() {
    var $cb = $(this).find("checkbox");
    if (!$cb.attr("checked")) {
      $cb.attr("checked", true);
    } else {
      $cb.attr("checked", false);
    }
  });

I hope it helped.

try this:

 <label><input type="checkbox">List value 1</label> <label><input type="checkbox">List value 2</label> <label><input type="checkbox">List value 3</label>

Here are the steps to do just that:

  1. Add an id attribute to the checkbox input element, eg id="check1"
  2. Put all the markup that should respond to the click in a label element and add a for attribute with id value in 1 above eg for="check1"

 <div class="list-checkbox list-group list-button mx-auto mt-2"> <button class="list-group-item d-flex justify-content-between align-items-center"> <label for="check1"> <span>Option 1</span> <label class="checkboxCustom my-auto"> <input type="checkbox" checked="checked" id="check1"> <span class="checkmark"></span> </label> </label> </button> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM