Created
January 22, 2014 12:31
-
-
Save csrui/8557944 to your computer and use it in GitHub Desktop.
work in progress - Grabs a <select> a replaces it by a clickable ul/li for better formatting
This file contains hidden or 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
(function( $ ) { | |
var $main_select = {}; | |
$.fn.tognsort = function( options ) { | |
var options = $.extend({}, $.fn.tognsort.defaults, options ); | |
$main_select = this; | |
if (options.parent === null) { | |
$main_select.hide(); | |
} | |
$list = renderList(); | |
if (options.allowSorting) { | |
$list.sortable({ | |
handle: ".handle" | |
}); | |
$list.on("sortstop", function( event, ui ) { | |
var sortedIDs = $.fn.tognsort.getOrder(this); | |
options.onSorted.call( this, sortedIDs ); | |
}); | |
} | |
}; | |
$.fn.tognsort.defaults = { | |
parent: null, | |
allowSorting: false, | |
onSorted : function() {} | |
} | |
var renderList = function() { | |
var object = $main_select; | |
var $list = $('<ul/>'); | |
$list.addClass('tognsort'); | |
$list.insertAfter(object); | |
// Preselect values | |
var to_preselect = []; | |
$main_select.find("option:selected").each(function() { | |
to_preselect.push($( this ).val()); | |
}); | |
// Replicate existing select options | |
object.find('option').each(function() { | |
var $title = $('<span class="title">' + $(this).html() + '</span>'); | |
var $li = $('<li/>') | |
.append('<div class="handle glyphicon glyphicon-align-justify"></div>') | |
.append($title) | |
.data('value', $(this).val()) | |
.appendTo($list); | |
if (to_preselect.indexOf($(this).val()) != -1) { | |
$li.addClass('selected'); | |
} | |
$title | |
.click(function() { | |
var $li = $(this).closest('li'); | |
$main_select.find('option[value="' + $li.data('value') + '"]').attr('selected', function(idx, oldAttr) { | |
return !oldAttr; | |
}); | |
$li.toggleClass('selected'); | |
}) | |
}); | |
return $list; | |
}; | |
$.fn.tognsort.getOrder = function(list) { | |
var new_order = []; | |
$(list).find('li').each(function(key, item) { | |
if ($(item).hasClass('selected')) { | |
new_order.push($(item).data('value')); | |
} | |
}); | |
return new_order; | |
}; | |
}( jQuery )); |
This file contains hidden or 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
.tognsort { | |
list-style: none; | |
padding-left: 0; | |
li { | |
padding: .5em; | |
margin-bottom: .5em; | |
} | |
.handle { | |
cursor: move; | |
} | |
.title { | |
margin-left: 1em; | |
cursor: pointer; | |
} | |
.selected { | |
background: #DDD; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment