Javascript 选择2提交值而不是id

Javascript 选择2提交值而不是id,javascript,jquery,ruby-on-rails,jquery-select2,select2-rails,Javascript,Jquery,Ruby On Rails,Jquery Select2,Select2 Rails,我有Rails应用程序,可以从中选择国家: =f.input:country,label:t(“heading.country”),as::string,input\u html:{class:'select2',数据:{allowad:true,depth:0,id:@post.location.country.id,url:search\u locations\u path} Select2通过以下方式附加到此元素: loadSelect2 = (selector = '.select2')

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

=f.input:country,label:t(“heading.country”),as::string,input\u html:{class:'select2',数据:{allowad:true,depth:0,id:@post.location.country.id,url:search\u locations\u 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
加载初始值,从
数据id
内部
initSelection
加载id

当我选择国家并提交表单时,一切正常:
post_参数['country']
等于所选国家的id,但如果我提交表单时不更改所选值(保留默认值),则
post_参数['country']
helds
value
,而不是
id

我哪里错了?如何修复?

将您的输入更改为:

=f.input:country,label:t(“heading.country”),as::string,input\u html:{value:@post.location.country.id,class:'select2',数据:{allowad:true,depth:0,title:@post.location.country.title,url:search\u locations\u path}

…这样,您将在输入值中存储初始选定元素的
id
,并在数据属性中而不是
data id
存储元素的标题
data title
(当然,您可以将
data id
保持不变,以备将来使用)。 此外,您还需要重构
initSelection
函数以使用这些新值,如下所示:

initSelection:(元素,回调)->
回拨
id:$(元素).val(),

标题:$(元素).数据('title')

rails代码在哪里创建输入?@МаъСъъъ添加了创建输入的代码似乎输入不是一个集合@МаъСъъъъ什么意思?输入是单个值,更多值通过ajax调用加载,该调用返回数组:[{id:1,title:'France'},{id:2,title:'Germany'},]