Skip to content

Instantly share code, notes, and snippets.

@NVentimiglia
Created June 3, 2015 04:22
Show Gist options
  • Save NVentimiglia/81923dfea51edcaa91fb to your computer and use it in GitHub Desktop.
Save NVentimiglia/81923dfea51edcaa91fb to your computer and use it in GitHub Desktop.
Boostrap dropdown proxy plugin. Link a bootstrap dropdown selection to a hidden form element.
Do <select>'s drive you crazy ? Want to use a bootstrap dropdown in your forms? now you can.
This plugin works by binding the dropdown to a hidden form element.
// HTML
<div class="navbar-right navbar-collapse collapse" id="navbar-collapse2">
<ul class="nav navbar-nav">
<li class="form-groupdropdown proxy-select" data-target="#Role2">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">All Catalogs</a>
<ul class="dropdown-menu" role="menu">
<li><a href="#" value="0">All Catalogs</a></li>
<li><a href="#" value="1">Global Catalogs</a></li>
<li><a href="#" value="2">Group Catalogs</a></li>
<li><a href="#" value="3">Surcharges</a></li>
</ul>
</li>
</ul>
<form class="navbar-form navbar-left" role="search">
<input type="hidden" id="Role" />
<div class="form-group">
<input type="text" id="Role2" class="form-control" placeholder="Group Filter">
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Name Filter">
</div>
<button type="submit" class="btn btn-default">Search</button>
</form>
</div>
</div>
// JS
<script type="text/javascript">
$(document).ready(function () {
$('.proxy-select').proxySelect();
});
$.fn.proxySelect = function () {
var options = $(this).find("li a");
var targetId = this.attr("data-target");
var root = this.find(".dropdown-toggle")[0];
var def = root.innerHTML;
var car = " <span class=\"caret\"></span>";
//get selected
var option = $.grep(options, function (n, i) {
return n === targetId;
});
// default title
if (option.length === 0) {
$(root).html(def + car);
} else {
$(root).html(option.attr("value") + car);
}
// wire
options.each(function () {
$(this).on("click", function () {
// update values
var oval = $(this).attr("value");
//set title
$(root).html(oval + car);
//set hidden
$(targetId).val(oval);
});
});
};
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment