Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
neoteric_fedkit / test / dummy / app / assets / javascripts / select-init.js
Size: Mime:
$(function () {
  initSelect2s = function (scope) {
    $(scope).find('.select2').select2({
      width: '80%'
    })

    $(scope).find('.select2-remote').each(function () {
      const element = this
      var getUrl = element.dataset.url
      console.log(element)

      if (element.dataset.dependent) {
        getUrl = getUrlForItemType.bind(element)
        $(document).on('change', element.dataset.dependent, function () {
          element.value = null
          $(element).trigger('change')
        })
      }

      const fields = JSON.parse(element.dataset.fields)
      const displayName = element.dataset.displayName
      const responseRoot = element.dataset.responseRoot
      const minimumInputLength = element.dataset.minimumInputLength
      const order = element.dataset.order

      var selectOptions = {
        minimumInputLength: minimumInputLength,
        allowClear: true,
        placeholder: 'Search',
        width: '80%',
        ajax: {
          url: getUrl,
          dataType: 'json',
          delay: 250,
          cache: true,
          data: function (params) {
            var textQuery = { m: 'or' }
            fields.forEach(function (field) {
              if (field == 'id') {
                textQuery[field + '_eq'] = params.term
              } else {
                textQuery[field + '_contains'] = params.term
              }
            })

            var query = {
              order: order,
              q: {
                groupings: [textQuery],
                combinator: 'and'
              }
            }

            return query
          },
          processResults: function (data) {
            if (data.constructor == Object) {
              data = data[responseRoot]
            }

            return {
              results: jQuery.map(data, function (resource) {
                if (!resource[displayName]) {
                  resource[displayName] = 'No display name for id #' + resource.id.toString()
                }
                return {
                  id: resource.id,
                  text: resource[displayName].toString()
                }
              })
            }
          }
        }
      }

      $(this).select2(selectOptions)
        .find('option[selected]').prop('selected', 'selected') // Fix Select2 not picking up preselected values
        .trigger('change')
    })
  }
})

function getUrlForItemType () {
  const selectedType = document.querySelector(this.dataset.dependent).value
  const lookup = JSON.parse(this.dataset.urls)

  return lookup[selectedType]
}