选择2提交值而不是id

时间:2014-12-05 10:48:17

标签: javascript jquery ruby-on-rails jquery-select2 select2-rails

我有Rails应用程序,我可以从中选择国家/地区:

= f.input :country, label: t("heading.country"), as: :string, input_html: { class: 'select2', data: { allowadd: true, depth: 0, id: @post.location.country.id, url: search_locations_path } }

Select2通过以下方式附加到此元素:

loadSelect2 = (selector = '.select2') ->
  $(@).select2
    ajax:
      data: (term, page) ->
        search: term
        depth: $(@).data('depth')
      results: (data, page) ->
        results: data
      url: $(@).data('url')
    createSearchChoice: (term, data) ->
      if $(data).filter(->
        @title.localeCompare(term) is 0
      ).length is 0
        id: term
        title: term
    createSearchChoicePosition: 'bottom'
    formatResult: (item) ->
      item.title
    formatSelection: (item) ->
      item.title
    initSelection: (element, callback) ->
      callback
        id: $(element).data('id')
        title: $(element).val()

所以,如你所见,我可以选择国家或添加一个国家(如果没有国家/地区)。此外,我正在输入val中的初始值和来自data-id内的initSelection的ID。

当我选择国家/地区并提交表单时,一切正常:post_params['country']等于所选国家/地区的ID,但如果我提交表单而未更改选定的值(保留默认值),则post_params['country']持有{ {1}},而不是value

我错在哪里以及如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

将您的输入更改为:

= f.input :country, label: t("heading.country"), as: :string, input_html: { value: @post.location.country.id, class: 'select2', data: { allowadd: true, depth: 0, title: @post.location.country.title, url: search_locations_path } }

...因此,在输入值中,您将存储最初选定元素的id,而在数据属性而不是data-id中,您将存储元素标题{{ 1}}(当然,您可以将data-title保留原样以备将来使用)。 您还需要重构data-id函数以使用以下新值:

initSelection

相关问题