Last active
March 23, 2025 18:08
-
-
Save renius/4736798 to your computer and use it in GitHub Desktop.
# Convert .bootstrap-select elements to Bootstrap Dropdown Group
# Assumes jQuery and Bootstrap scripts already linked
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 .bootstrap-select elements to Bootstrap Dropdown Group | |
# Assumes jQuery and Bootstrap scripts already linked | |
# !!! require jQuery 1.7.2 - 1.8.3 | |
# | |
# Expected markup: | |
# <select class="span1" id="car_engine_type" name="car[engine_type]" style="margin-left: 30px"> | |
# <option value="">fuel</option> | |
# <option value="diesel">diesel</option> | |
# <option value="gasoline">gasoline</option> | |
# <option value="hybrid">hibrid</option> | |
# </select> | |
# | |
# Anton Dyachuk 2013 <[email protected]> | |
# | |
# Inspired by : John Rocela 2012 <[email protected]> | |
# From: http://blog.iamjamoy.com/convert-select-boxes-to-a-fancy-html-dropdown | |
# | |
# updates from Colin Faulkingham (https://gist.github.com/2320588) | |
# and Frank Basti (http://jsfiddle.net/xuAQv/13) | |
jQuery ($) -> | |
$(".bootstrap-select").each (i, e) -> | |
current = $(e).find("option:selected").html() or " " | |
val = $(e).find("option:selected").val() | |
name = e.name | |
btn_group = $(document.createElement('div')) | |
.addClass('btn-group') | |
top_button = $(document.createElement('a')) | |
.addClass("btn #{$(e).attr('class')}") | |
.html(current) | |
caret = $(document.createElement('a')) | |
.addClass('btn dropdown-toggle') | |
.attr('data-toggle', 'dropdown') | |
.html($(document.createElement('span')) | |
.addClass('caret') | |
) | |
ul = $(document.createElement('ul')) | |
.addClass('dropdown-menu from-selector') | |
input = $(document.createElement('input')) | |
.attr({ | |
type: 'hidden', | |
value: val, | |
name: name, | |
id: e.id, | |
class: $(e).attr('class') | |
}) | |
btn_group | |
.append(top_button) | |
.append(caret) | |
.append(ul) | |
.append(input) | |
options = $(e).find('option') | |
options.each (option, v) -> | |
li = $(document.createElement('li')) | |
.append( | |
$(document.createElement('a')) | |
.attr({value: v.value}) | |
.html(v.value) | |
) | |
ul.append li | |
$(e).parent().append btn_group | |
$(e).remove() | |
new_options = $(".dropdown-menu.from-selector a") | |
new_options.die 'click' | |
new_options.live 'click', (e) -> | |
select = $(@).parents('.btn-group') | |
select.find("input[type=hidden]").val($(@).attr('value')) | |
select.find(".btn:eq(0)").html $(@).html() | |
select.find("input[type=hidden]").trigger('change') | |
e.preventDefault() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment