Search code examples
javascripthtmlcss

How to create checkbox inside dropdown?


I want to create a multiple selection dropbox list. Actually I have to select more than one option using a dropdown menu. When I simply do this as shown below:

    <select>
     <option><input type="checkbox"></option>
    </select>

Then checkbox is showing in front of dropdown field. But I want to create it for each option not for as a whole so that I can select more than one option. Is there any way to do this?


Solution

  • Here is a simple dropdown checklist:

    var checkList = document.getElementById('list1');
    checkList.getElementsByClassName('anchor')[0].onclick = function(evt) {
      if (checkList.classList.contains('visible'))
        checkList.classList.remove('visible');
      else
        checkList.classList.add('visible');
    }
    .dropdown-check-list {
      display: inline-block;
    }
    
    .dropdown-check-list .anchor {
      position: relative;
      cursor: pointer;
      display: inline-block;
      padding: 5px 50px 5px 10px;
      border: 1px solid #ccc;
    }
    
    .dropdown-check-list .anchor:after {
      position: absolute;
      content: "";
      border-left: 2px solid black;
      border-top: 2px solid black;
      padding: 5px;
      right: 10px;
      top: 20%;
      -moz-transform: rotate(-135deg);
      -ms-transform: rotate(-135deg);
      -o-transform: rotate(-135deg);
      -webkit-transform: rotate(-135deg);
      transform: rotate(-135deg);
    }
    
    .dropdown-check-list .anchor:active:after {
      right: 8px;
      top: 21%;
    }
    
    .dropdown-check-list ul.items {
      padding: 2px;
      display: none;
      margin: 0;
      border: 1px solid #ccc;
      border-top: none;
    }
    
    .dropdown-check-list ul.items li {
      list-style: none;
    }
    
    .dropdown-check-list.visible .anchor {
      color: #0094ff;
    }
    
    .dropdown-check-list.visible .items {
      display: block;
    }
    <div id="list1" class="dropdown-check-list" tabindex="100">
      <span class="anchor">Select Fruits</span>
      <ul class="items">
        <li><input type="checkbox" />Apple </li>
        <li><input type="checkbox" />Orange</li>
        <li><input type="checkbox" />Grapes </li>
        <li><input type="checkbox" />Berry </li>
        <li><input type="checkbox" />Mango </li>
        <li><input type="checkbox" />Banana </li>
        <li><input type="checkbox" />Tomato</li>
      </ul>
    </div>