Created
April 25, 2014 04:44
-
-
Save tkawa/11277896 to your computer and use it in GitHub Desktop.
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
# jQuery optgroupDoubleSelect plugin | |
# Rewrite of jDoubleSelect | |
# Copyright (c) Giovanni Casassa & Toru Kawamura | |
# | |
# Dual licensed under the MIT (MIT-LICENSE.txt) | |
# and GPL (GPL-LICENSE.txt) licenses. | |
# | |
# http://www.senamion.com/blog/jDoubleSelect.html | |
jQuery ($) -> | |
$.fn.optgroupDoubleSelect = (options) -> | |
options = $.extend( | |
text: '' | |
, options) | |
@each -> | |
$select = $(@) | |
groupSelectName = ($select.attr('id') || $select.attr('name') || 'internalName') + '_DS' | |
groupSelectId = "##{groupSelectName}" | |
valueSelectName = groupSelectName + '2' | |
valueSelectId = "##{valueSelectName}" | |
# build groupSelect | |
$groupSelect = $("<select id='#{groupSelectName}' class='#{options.selectClass}'></select>") | |
$select.children('optgroup').each -> | |
$optgroup = $(@) | |
$selectOption = $("<option value='#{@label}'>#{@label}</option>") | |
if $optgroup.prop('disabled') | |
$selectOption.prop('disabled', $optgroup.prop('disabled')) | |
else if $optgroup.find(':selected').val() | |
$selectOption.prop('selected', true) | |
$groupSelect.append($selectOption) | |
$select.hide().after($groupSelect) | |
$groupSelect.after("<span class='text_DS'>#{options.text}</span>") | |
$(document).on 'change', groupSelectId, -> | |
# remove old element, add new select, bind change event and trigger it | |
$(valueSelectId).remove() | |
# build valueSelect | |
$valueSelect = $("<select id='#{valueSelectName}' class='#{options.selectClass}'></select>") | |
$optgroup = $select.children("optgroup[label='#{@value}']").clone() | |
$valueSelect.append($optgroup) | |
$select.nextAll('.text_DS').after($valueSelect) | |
if $optgroup.children('option').get().some((selectOption) -> selectOption.value.toString() == $select.val().toString()) | |
$valueSelect.val($select.val()) | |
else | |
$valueSelect.children('option').first().prop('selected', true) | |
$valueSelect.trigger('change') | |
$(document).on 'change', valueSelectId, -> | |
$select.val(@value) | |
# initial trigger | |
$(valueSelectId).trigger('change') | |
$(groupSelectId).trigger('change') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment