28

I'm trying to customize a bootstrap dropdown with checkboxes and if I select a checkbox from dropdown the label name I want to be written on input dropdown delimited with ';' like in uploaded picture when dropdown is closed.

Here is a fiddle example.

enter image description here

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
BurebistaRuler
  • 6,209
  • 11
  • 48
  • 66

3 Answers3

16

Not the most elegant solution - you will probably want to refine this somewhat, but this might get you started:

$(document).ready(function() {
    $("ul.dropdown-menu input[type=checkbox]").each(function() {
        $(this).change(function() {
            var line = "";
            $("ul.dropdown-menu input[type=checkbox]").each(function() {
                if($(this).is(":checked")) {
                    line += $("+ span", this).text() + ";";
                }
            });
            $("input.form-control").val(line);
        });
    });
});
Matthew Layton
  • 39,871
  • 52
  • 185
  • 313
11

I know it's a old question but still, you can use this library to do almost (except the exact design you asked) what you want http://davidstutz.github.io/bootstrap-multiselect/#getting-started

David Létourneau
  • 1,250
  • 2
  • 19
  • 39
2

The following code works in Bootstrap 4.1 if you add a function to show the menu on hover, but when you click the < li > then your checkboxes becomes unclickable. Anybody having a better solution please provide.

<ul class="dropdown-menu dropdown-menu-form">
  <li><label class="checkbox"><input type="checkbox">One</label></li>
  <li><label class="checkbox"><input type="checkbox">Two</label></li>
</ul>

And add these JS codes:

// Allow Bootstrap dropdown menus to have forms/checkboxes inside, 
// and when clicking on a dropdown item, the menu doesn't disappear.
$(document).on('click', '.dropdown-menu.dropdown-menu-form', function(e) {
  e.stopPropagation();
});

UPDATE

The below code is working good but checkboxes events are fired twice so had to choose the onchange event instead of onclick

<ul class="dropdown-menu dropdown-menu-form">
  <li><label class="checkbox"><input type="checkbox" onchange="some()">One</label></li>
  <li><label class="checkbox"><input type="checkbox" onchange="some()">Two</label></li>
</ul>

and the jquery code as follows:

$(document).on('click', '.dropdown-menu', function (e) {
    e.stopPropagation();
});
sam
  • 1,800
  • 1
  • 25
  • 47