How to get Dropdown Menu with Checkboxes

14,719

Can easily get from a google search, Try this

HTML

<br/>
<div class="container">
  <div class="row">
       <div class="col-lg-12">
     <div class="button-group">
        <button type="button" class="btn btn-default btn-sm dropdown-toggle" data-toggle="dropdown"><span class="glyphicon glyphicon-cog"></span> <span class="caret"></span></button>
<ul class="dropdown-menu">
  <li><a href="#" class="small" data-value="option1" tabIndex="-1"><input type="checkbox"/>&nbsp;Option 1</a></li>
  <li><a href="#" class="small" data-value="option2" tabIndex="-1"><input type="checkbox"/>&nbsp;Option 2</a></li>
  <li><a href="#" class="small" data-value="option3" tabIndex="-1"><input type="checkbox"/>&nbsp;Option 3</a></li>
  <li><a href="#" class="small" data-value="option4" tabIndex="-1"><input type="checkbox"/>&nbsp;Option 4</a></li>
  <li><a href="#" class="small" data-value="option5" tabIndex="-1"><input type="checkbox"/>&nbsp;Option 5</a></li>
  <li><a href="#" class="small" data-value="option6" tabIndex="-1"><input type="checkbox"/>&nbsp;Option 6</a></li>
</ul>
  </div>
</div>
  </div>
</div>

JS

var options = [];

$( '.dropdown-menu a' ).on( 'click', function( event ) {

   var $target = $( event.currentTarget ),
       val = $target.attr( 'data-value' ),
       $inp = $target.find( 'input' ),
       idx;

   if ( ( idx = options.indexOf( val ) ) > -1 ) {
      options.splice( idx, 1 );
      setTimeout( function() { $inp.prop( 'checked', false ) }, 0);
   } else {
      options.push( val );
      setTimeout( function() { $inp.prop( 'checked', true ) }, 0);
   }

   $( event.target ).blur();

   console.log( options );
   return false;
});

or check this,

Share:
14,719
Skywalker
Author by

Skywalker

Updated on June 14, 2022

Comments

  • Skywalker
    Skywalker almost 2 years

    I am trying for a dropdown menu with checkboxes in it? How do I proceed? below is my Html snippet I am trying.

    <div class="form-group col-lg-3">
        <div *ngFor="let option of options">
            <select>
                <input type="checkbox" name="options" value="{{option.value}}" [(ngModel)]="option.checked" /> {{option.name}}
            </select>
        </div>
    </div>
    
    • Harry Joy
      Harry Joy over 6 years
      I think you need option tag inside select.
    • Skywalker
      Skywalker over 6 years
      Yes options can be added, but they dont turn out to be checkboxes, they would be simple options in the drop-down
    • Harry Joy
      Harry Joy over 6 years
      Use input inside option?
  • Skywalker
    Skywalker over 6 years
    Exactly what I needed, Thank you so much.