Skip to content

Instantly share code, notes, and snippets.

@entrity
Last active December 17, 2015 15:19
Show Gist options
  • Save entrity/5630999 to your computer and use it in GitHub Desktop.
Save entrity/5630999 to your computer and use it in GitHub Desktop.
Integrate select2's autocomplete (using ajax to get remote options) with x-editable
# Functions to handle integration of x-editable w/ select2 w/ ajax source.
# Usage is as follows:
# <a href='#' id='elem' data-type='select2' data-name='template_id' data-url='/crm/task_builders/4' data-id=4></a>
# <script>
# $('#elem').editableSelect2Templates();
# </script>
do () ->
# Convenience method for adding x-editable + select2 behaviour to an <a>.
# Options include queryUrl, url, params, send, placeholder, allowClear, minimumInputLength, query, data, displayKey
# Options that pertain to select2, not x-editable, must be set in options, not data attributes of the DOM element.
# If query is not set in options, then queryUrl must be set in options.
$.fn.editableSelect2 = (options={}, query=null) ->
$.each this, () ->
dataset = this.dataset
$(this).editable
params: options.params || window.config.xEditableParams
tpl: buildHiddenInputContainingDataset(dataset)
send: options.send || 'always'
select2:
placeholder: options.placeholder || '(select)'
allowClear: options.allowClear || true
minimumInputLength: options.minimumInputLength || 1
formatSelection: hackToMakeTextAppearAfterInputCloses
query: query || defaultQuery(options)
# Referenced in editableSelect2
defaultQuery = (options) ->
(query) ->
key = options.displayKey || 'name'
data = options.data || {}
data[key] ||= query.term
$.ajax(
url: options.queryUrl
dataType: 'json'
data: data
).done (data) ->
results = ({text:datum[key], id:datum.id} for datum in data)
query.callback {results:results}
# Referenced in editableSelect2
hackToMakeTextAppearAfterInputCloses = (object, container) ->
if typeof(object.text) != 'undefined'
container.closest('span.editable-container').prev()[0].innerHTML = object.text
object.text
# Referenced in editableSelect2
buildHiddenInputContainingDataset = (dataset, beginning) ->
output = beginning || "<input type=hidden"
output += " data-"+k+"="+v for k,v of dataset
output + ">"
$.fn.editableSelect2Templates = (options={}) ->
this.editableSelect2 options, (query) ->
dataset = this.element[0].dataset
$.ajax(
url: '/marketing/templates'
dataType: 'json'
data: {task_builder_id: dataset.id, name:query.term}
).done (data) ->
results = ({text:d.name, id:d.id} for d in data)
query.callback {results:results}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment