jdave jdave - 26 days ago 9
CSS Question

Bootstrap drop down with check box(s) allowing for multiple check boxes instead of just one

I have a Bootstrap drop down menu that allows a user to add a check box next to an item in the drop down list. However, the user is able to add multiple check boxes - the desired behavior is that a user should only be able to select one check box. If a user has selected one check box the other check box should be removed.



$("document").ready(function() {

$('.dropdown-menu').on('click', function(e) {
if($('.checkbox').count() > 1){
if($(this).hasClass('dropdown-menu-form')) {
e.stopPropagation();
}
}

});
});

.dropdown-menu-form {
padding: 5px 10px 0;
max-height: 100px;
overflow-y: scroll;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<div class="dropdown">
<a class="dropdown-toggle btn" data-toggle="dropdown" href="#">
Toggle dropdown
<b class="caret"></b>
</a>
<ul class="dropdown-menu dropdown-menu-form" role="menu">
<li>
<label class="checkbox">
<input type="checkbox">Checkbox 1
</label>
</li>
<li>
<label class="checkbox">
<input type="checkbox">Checkbox 2
</label>
</li>
<li>
<label class="checkbox">
<input type="checkbox">Checkbox 2
</label>
</li>
<li>
<label class="checkbox">
<input type="checkbox">Checkbox 2
</label>
</li>
<li>
<label class="checkbox">
<input type="checkbox">Checkbox 2
</label>
</li>
<li>
<label class="checkbox">
<input type="checkbox">Checkbox 3
</label>
</li>
</ul>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>





I tried to implement something with the count of the number of klass of
.checkbox
however that did not work. I am just looking to have the behavior if the user clicks a check box the previous check box will be removed.

Answer

Checkboxes are created to allow multiple checks, think of it as you can have this, that, and that. You are looking for a radio button. Radio buttons are treated as a you get this or you get that.

Try This

<li>
        <label class="radio-btn">
            <input type="radio">
            Radio 1
        </label>
    </li>

JS

$("document").ready(function() {

  $('.dropdown-menu').on('click', function(e) {
    if($('.radio-btn').count() > 1){
           if($(this).hasClass('dropdown-menu-form')) {
          e.stopPropagation();
      }
    }

  });
});