Created
December 10, 2012 17:23
-
-
Save NIA/4251971 to your computer and use it in GitHub Desktop.
Convert .select elements to Bootstrap Dropdown Group
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*! | |
* Convert .select elements to Bootstrap Dropdown Group | |
* Assumes jQuery and Bootstrap scripts already linked | |
* | |
* Expected markup: | |
* | |
* <div id="someId" data-name="someName" class="select someClass"> | |
* <div class="option selected" data-value="1"> Item 1 <i class="icon-ok"></i></div> | |
* <div class="option" data-value="2"> Item 2 <span>some html</span></div> | |
* <div class="option" data-value="3"> Item 3 <img src="little.img"></div> | |
* </div> | |
* | |
* Author: John Rocela 2012 <[email protected]> | |
* From: http://blog.iamjamoy.com/convert-select-boxes-to-a-fancy-html-dropdown | |
* | |
* Inspired by updates from Colin Faulkingham (https://gist.github.com/2320588) | |
* and Frank Basti (http://jsfiddle.net/xuAQv/13) | |
* | |
* Modified: Ivan Novikov (http://github.com/NIA), Dec 2012 | |
* Changed: use classes on divs instead of select/option tags, | |
* thus allow arbitrary html inside options, | |
* propagate original element classes to buttons, | |
* fixed IE compatibility and rounded corners of first .btn, | |
* avoid using javascript: pseudo-protocol | |
*/ | |
jQuery(function($){ | |
$('.select').each(function(i, e){ | |
if (!($(e).data('convert') == 'no')) { | |
$(e).hide().removeClass('select'); | |
var current = $(e).find('.option.selected').html() || ' '; | |
var val = $(e).find('.option.selected').data('value'); | |
var name = $(e).data('name') || ''; | |
$(e).parent().append('<div class="btn-group" id="select-group-' + i + '" />'); | |
var select = $('#select-group-' + i); | |
select.html('<a class="btn ' + $(e).attr('class') + '" type="button">' + current + '</a><a class="btn dropdown-toggle ' + $(e).attr('class') + '" data-toggle="dropdown" href="#"><span class="caret"></span></a><ul class="dropdown-menu"></ul><input type="hidden" value="' + val + '" name="' + name + '" id="' + $(e).attr('id') + '" class="' + $(e).attr('class') + '" />'); | |
$(e).find('.option').each(function(o,q) { | |
select.find('.dropdown-menu').append('<li><a href="#" data-value="' + $(q).data('value') + '">' + $(q).html() + '</a></li>'); | |
}); | |
select.find('.dropdown-menu a').click(function(e) { | |
select.find('input[type=hidden]').val($(this).data('value')).change(); | |
select.find('.btn:eq(0)').html($(this).html()); | |
e.preventDefault(); | |
}); | |
$(e).remove(); | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment