Skip to content

Instantly share code, notes, and snippets.

@nelyj
Created November 6, 2015 06:10
Show Gist options
  • Save nelyj/bd8f445c25276465baa8 to your computer and use it in GitHub Desktop.
Save nelyj/bd8f445c25276465baa8 to your computer and use it in GitHub Desktop.
$.fn.extend
dynamicSelectable: ->
$(@).each (i, el) ->
new DynamicSelectable($(el))
class DynamicSelectable
constructor: ($select) ->
@init($select)
init: ($select) ->
@urlTemplate = $select.data('dynamicSelectableUrl')
@$targetSelect = $($select.data('dynamicSelectableTarget'))
$select.on 'change', =>
@clearTarget()
url = @constructUrl($select.val())
if url
$.getJSON url, (data) =>
$.each data, (index, el) =>
@$targetSelect.append "<option value='#{el.id}'>#{el.name}</option>"
# reinitialize target select
@reinitializeTarget()
else
@reinitializeTarget()
reinitializeTarget: ->
@$targetSelect.trigger("change")
clearTarget: ->
@$targetSelect.html('<option></option>')
constructUrl: (id) ->
if id && id != ''
@urlTemplate.replace(/:.+_id/, id)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment