Skip to content

Instantly share code, notes, and snippets.

@ljkbennett
Last active December 20, 2015 16:49
Show Gist options
  • Save ljkbennett/6164476 to your computer and use it in GitHub Desktop.
Save ljkbennett/6164476 to your computer and use it in GitHub Desktop.
Coffeescript for a dropdown that can contain checkboxes and not close when one is clicked, allowing multiple checks. The button text is updated to reflect the values selected.
<div class="btn-group">
<a class="btn dropdown-toggle" data-toggle="dropdown" href="#">
Please select
</a>
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu">
<li><input type="checkbox" name="option1" id="option1" value="option1"/><label for="option1">Option 1</label</li>
<li><input type="checkbox" name="option2" id="option2" value="option2"/><label for="option2">Option 2</label</li>
<li><input type="checkbox" name="option3" id="option3" value="option3"/><label for="option3">Option 3</label</li>
</ul>
</div>
$(document).ready ->
$('.dropdown-menu input, .dropdown-menu label').click (event) ->
event.stopPropagation()
$('.dropdown-menu input').change (event) ->
$btnGroup = $(this).closest(".btn-group")
$menuItems = $btnGroup.find(".dropdown-menu input:checked")
selected = []
$menuItems.each (index, item) ->
selected.push($(item).val())
title = ""
if selected.length > 0
title = selected.join(", ")
else
title = "Please select"
$btnGroup.find(".btn").text(title)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment