Skip to content

Instantly share code, notes, and snippets.

@cfaulkingham
Created April 6, 2012 14:58
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cfaulkingham/2320588 to your computer and use it in GitHub Desktop.
Save cfaulkingham/2320588 to your computer and use it in GitHub Desktop.
Convert Select ELement's to Dropdown group
/*!
* Convert <select> elements to Dropdown Group
*
* Author: John Rocela 2012 <me@iamjamoy.com>
* Update: Fixed issue with selected showing value instead of text Colin Faulkingham <colin.faulkingham@gmail.com> 2012
*/
jQuery(function($){
$('select').each(function(i, e){
if (!($(e).data('convert') == 'no')) {
$(e).hide().wrap('<div class="btn-group" id="select-group-' + i + '" />');
var select = $('#select-group-' + i);
var current = ($(e).val()) ? $(e).val(): '&nbsp;';
var textValue = '';
$(e).find('option').each(function(o,q) {
if(current == $(q).attr('value')){
textValue = $(q).text();
}
});
select.html('<input type="hidden" value="' + $(e).val() + '" name="' + $(e).attr('name') + '" id="' + $(e).attr('id') + '" class="' + $(e).attr('class') + '" /><a class="btn" href="javascript:;">' + textValue + '</a><a class="btn dropdown-toggle" data-toggle="dropdown" href="javascript:;"><span class="caret"></span></a><ul class="dropdown-menu"></ul>');
$(e).find('option').each(function(o,q) {
select.find('.dropdown-menu').append('<li><a href="javascript:;" data-value="' + $(q).attr('value') + '">' + $(q).text() + '</a></li>');
if ($(q).attr('selected')) select.find('.dropdown-menu li:eq(' + o + ')').click();
});
select.find('.dropdown-menu a').click(function() {
select.find('input[type=hidden]').val($(this).data('value')).change();
select.find('.btn:eq(0)').text($(this).text());
});
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment