Skip to content

Instantly share code, notes, and snippets.

@tkawa
Created April 25, 2014 04:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tkawa/11277896 to your computer and use it in GitHub Desktop.
Save tkawa/11277896 to your computer and use it in GitHub Desktop.
# 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