How to use Checkbox inside Select Option

前端 未结 12 2252
夕颜
夕颜 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:52

    You cannot place checkbox inside select element but you can get the same functionality by using HTML, CSS and JavaScript. Here is a possible working solution. The explanation follows.

    enter image description here


    Code:

    var expanded = false;
    
    function showCheckboxes() {
      var checkboxes = document.getElementById("checkboxes");
      if (!expanded) {
        checkboxes.style.display = "block";
        expanded = true;
      } else {
        checkboxes.style.display = "none";
        expanded = false;
      }
    }
    .multiselect {
      width: 200px;
    }
    
    .selectBox {
      position: relative;
    }
    
    .selectBox select {
      width: 100%;
      font-weight: bold;
    }
    
    .overSelect {
      position: absolute;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
    }
    
    #checkboxes {
      display: none;
      border: 1px #dadada solid;
    }
    
    #checkboxes label {
      display: block;
    }
    
    #checkboxes label:hover {
      background-color: #1e90ff;
    }

    Explanation:

    At first we create a select element that shows text "Select an option", and empty element that covers (overlaps) the select element (

    ). We do not want the user to click on the select element - it would show an empty options. To overlap the element with other element we use CSS position property with value relative | absolute.

    To add the functionality we specify a JavaScript function that is called when the user clicks on the div that contains our select element (

    ).

    We also create div that contains our checkboxes and style it using CSS. The above mentioned JavaScript function just changes

    value of CSS display property from "none" to "block" and vice versa.

    The solution was tested in the following browsers: Internet Explorer 10, Firefox 34, Chrome 39. The browser needs to have JavaScript enabled.


    More information:

    CSS positioning

    How to overlay one div over another div

    http://www.w3schools.com/css/css_positioning.asp

    CSS display property

    http://www.w3schools.com/cssref/pr_class_display.asp

提交回复
热议问题