Select2 represents value instead of id
I have a Rails application where I can select a country from:
= 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 is bound to this element:
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()
So, as you can see, I can select a country or add one (if there is no country). Also i load the initial value from input val
and id from data-id
inside initSelection
.
When I select a country and submit the form, everything works: post_params['country']
equals the selected country id, but if I submit the form without changing the selected value (leaving the default one), then it post_params['country']
swipes value
instead id
.
Where am I going wrong and how do I fix it?
source to share
Change your input to:
= 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 } }
... so that in the input value you store the id
originally selected element and in the data attributes instead data-id
you store the element title data-title
(of course you can leave it data-id
intact for future use). Also you need to refactor the function initSelection
to use these new values ββwith:
initSelection: (element, callback) ->
callback
id: $(element).val(),
title: $(element).data('title')
source to share