Skip to content

Instantly share code, notes, and snippets.

@tayfunoziserikan
Last active December 14, 2015 23:28
Show Gist options
  • Save tayfunoziserikan/5165529 to your computer and use it in GitHub Desktop.
Save tayfunoziserikan/5165529 to your computer and use it in GitHub Desktop.
Location selector
resources = []
selectors = []
$("select[data-locations=true]").each ->
el = $(this)
resources[el.data('parent')] = "/locations/#{el.data('resource')}.json"
selectors[el.data('parent')] = el.change ->
if el.data('child')
loadLocations(el.data('child'), el.data('parent'), el.val()) if el.val()
else
updateLocation el.val()
loadLocations = (child, parent, value) ->
console.log resources[child] + "?#{parent}_id=#{value}"
$.getJSON resources[child] + "?#{parent}_id=#{value}", (data) ->
pushOptions selectors[child], data
pushOptions = (selector, data) ->
removeOptions selector
$.each data, (i, item) ->
selector.append("<option value=" + item.id + ">" + item.name + "</option>").trigger("liszt:updated")
removeOptions = (selector) ->
# TODO remove all child select options
selector.find('option').remove()
updateLocation = (value) ->
text = []
$("select[data-locations=true]").each ->
el = $(this)
text.push el.find(':selected').text()
$('input.location').attr('value', value)
$('input.location-text').val(text.join(', ')).effect('highlight');
# Base location loader
if selectors['country']
$.getJSON resources['country'], (data) ->
pushOptions selectors['country'], data
@tayfunoziserikan
Copy link
Author

class LocationInput < SimpleForm::Inputs::Base
  def input
    base_locations = %w( country region town suburb )
    target_index = base_locations.index(reflection.name.to_s)

    display_value = options[:display_value] || object.send(reflection.name).try(:name)
    input_html_options[:style] ||= 'display:none;'

    input = template.content_tag(:div, class: 'input-append') do
      output = template.tag(:input, class: 'string location-text', size: target_index * 25, type: 'text', value: display_value)
      output << template.content_tag(:span, '<i class="icon-map-marker"></i>'.html_safe, class: 'add-on')
    end

    selectors = ''
    base_locations.each_with_index do |item, index|
      child = base_locations[index + 1]
      select_tag = template.select_tag("#{item}_id", nil, class: item, data: {locations: true, resource: item.pluralize,  validate: false, parent: item, child: child })
      selectors << select_tag unless index == target_index + 1
    end

    debug = template.content_tag(:div, selectors.html_safe, class: 'well location_combos')
    @builder.text_field(attribute_name, input_html_options) << input << debug
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment