How to use Checkbox inside Select Option

前端 未结 12 2131
夕颜
夕颜 2020-11-22 09:15

The client has given me a design which has a Select Option menu containing a checkbox together with the item name as individual items in the list. Is there anyway possible t

12条回答
  •  情话喂你
    2020-11-22 09:38

    Alternate Vanilla JS version with click outside to hide checkboxes:

    let expanded = false;
    const multiSelect = document.querySelector('.multiselect');
    
    multiSelect.addEventListener('click', function(e) {
      const checkboxes = document.getElementById("checkboxes");
        if (!expanded) {
        checkboxes.style.display = "block";
        expanded = true;
      } else {
        checkboxes.style.display = "none";
        expanded = false;
      }
      e.stopPropagation();
    }, true)
    
    document.addEventListener('click', function(e){
      if (expanded) {
        checkboxes.style.display = "none";
        expanded = false;
      }
    }, false)
    

    I'm using addEventListener instead of onClick in order to take advantage of the capture/bubbling phase options along with stopPropagation(). You can read more about the capture/bubbling here: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

    The rest of the code matches vitfo's original answer (but no need for onclick() in the html). A couple of people have requested this functionality sans jQuery.

    Here's codepen example https://codepen.io/davidysoards/pen/QXYYYa?editors=1010

提交回复
热议问题