Question

I am using Select2 to help select more than one option in a list. The problem is, is that I have the same code repeated when I want to have the same function for a portion of the form.

I would like to know a way to DRY up my code. Many thanks.

$(document).ready ->
   $(".universities-select2").each (i, e) ->
    select = $(e)
    options = {}
    if select.hasClass("ajax")
      options.ajax =
        url: select.data("source")
        dataType: "json"
        data: (term, page) ->
          q: term
          page: page
          per: 10

       results: (data, page) ->
        results: data

    options.dropdownCssClass = "bigdrop"
    options.multiple = true
    options.width = "200px"
    options.initSelection = (element, callback) ->
      id = undefined
      id = $(element).val()
      if id isnt null
        $.ajax(
          url: '/universities/multiple'
          dataType: "json"
          data:
            id: id
        ).done (data) ->
          results = undefined
          results = []
          callback data
          return

  select.select2 options
  return
return


$(document).ready ->
  $(".skills-select2").each (i, e) ->
    select = $(e)
    options = {}
    if select.hasClass("ajax")
      options.ajax =
        url: select.data("source")
        dataType: "json"
        data: (term, page) ->
          q: term
          page: page
          per: 10

        results: (data, page) ->
          results: datea

  options.dropdownCssClass = "bigdrop"
  options.multiple = true
  options.width = "200px"
  options.initSelection = (element, callback) ->
    id = undefined
    id = $(element).val()
    if id isnt null
      $.ajax(
        url: '/skills/multiple'
        dataType: "json"
        data:
          id: id
      ).done (data) ->
        results = undefined
        results = []
        callback data
        return

 select.select2 options
 return

return
Was it helpful?

Solution

You can just make the class name a variable and name your function

So:

setupSelect = (target) ->
  $(target).each (i, e) ->
    select = $(e)
    #etc


$ ->
  setupSelect('.universities-select2')
  setupSelect('.skills-select2')

Of course you can also select more than one class with a jquery selector, so if its just these 2 you can do this

$('.universities-select2, .skills-select2')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top