Skip to content

Instantly share code, notes, and snippets.

@gaulatti
Last active August 29, 2015 14:06
Show Gist options
  • Save gaulatti/cf4416e443c48f1d8dfc to your computer and use it in GitHub Desktop.
Save gaulatti/cf4416e443c48f1d8dfc to your computer and use it in GitHub Desktop.
Representing Checkboxes with Bootstrap Dropdowns
<!-- RadioButtons, about them the Dropdown will be filled -->
<input type="radio" name="ambito" class="selectable" value="1" data-caption="Ámbito 1">
<input type="radio" name="ambito" class="selectable" value="2" data-caption="Ámbito 2">
<input type="radio" name="ambito" class="selectable" value="3" data-caption="Ámbito 3">
<!-- Bootstrap Dropdown - empty -->
<div class="btn-group radio-selectable" data-radio="ambito">
<button type="button" class="btn btn-default dropdown-toggle btn-info" data-toggle="dropdown">
Seleccione <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu"></ul>
</div>
$('.radio-selectable').each(function() {
// Isolating Radiobutton name
radioName = $(this).attr('data-radio');
// Cleaning Dropdown
dropdown = $(this).children('.dropdown-menu');
$(dropdown).empty();
// Getting Radiobutton Items
$("input[type='radio'][name='" + radioName +"']").each(function() {
// Create ListItem
li = document.createElement("li");
// Hyperlink
hl = document.createElement("a");
hl.innerText = $(this).attr('data-caption');
hl.name = $(this).attr('name');
hl.href = "#" + $(this).attr('value');
// Append Behavior
$(hl).click(handlerSelectables);
// Add Items
$(li).append(hl);
$(dropdown).append(li);
});
});
function handlerSelectables(e) {
e.preventDefault();
// Aislar Parámetros
nombre = $(this).attr('name');
id = $(this).attr('href').replace('#', '');
// Obtener Checkbox
$("input[name='" + nombre + "']").removeAttr('checked');
$("input[name='" + nombre + "'][value='" + id + "']").attr('checked', true);
// Cambiar nombre al Select Original
select = $(".radio-selectable[data-radio='" + nombre + "']")
.children('button')
.html($(this).text() + ' <span class="caret"></span>');
}
input[type="radio"].selectable {
display: none;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment