【问题标题】:How to add new item dynamically with Select2 when No matches found?找不到匹配项时如何使用 Select2 动态添加新项目?
【发布时间】:2014-10-12 14:24:18
【问题描述】:

我在我的 Rails 应用程序中使用 select-2 来通过 Ajax 调用自动完成字段并允许多个值。

我的 CoffeScript 文件:

$(document).ready ->
  $('.select2').each (i, e) =>
    select = $(e)
    options =
      placeholder: select.data('placeholder')
      multiple: true
      width: "100%"      
      maximumSelectionSize: 20
      tokenSeparators: [",", " "]
      dropdownClass: 'bigdrop'      

    if select.hasClass('ajax')
      options.ajax =
        url: select.data('source')
        dataType: 'json'
        data: (term, page) ->
          q: term
          page: page
          per: 25
        results: (data, page) ->
          results: data.resources
          more: data.total > (page * 25) 

      options.dropdownCssClass = "bigdrop"

    select.select2(options)

如果服务器没有结果,我希望能够添加新项目,目前它不允许我添加新项目(未保存在服务器上并通过 Ajax 调用填充)。

【问题讨论】:

    标签: jquery ajax jquery-select2 select2-rails


    【解决方案1】:

    我必须使用类似以下的 createSearchChoice:

      createSearchChoice: (term, data) ->
        if $(data).filter(->
          this.text.localeCompare(term) is 0
        ).length is 0
          id: term
          text: term 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-12
      • 1970-01-01
      • 1970-01-01
      • 2013-05-01
      • 2014-10-15
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      相关资源
      最近更新 更多