Answer the question
In order to leave comments, you need to log in
How to submit id and not value in form with Select2?
There is an application on Ruby on Rails, where you can set the country on the post editing page, here is the input'a code (I use a simple form):
= 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 } }
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()
var loadSelect2;
loadSelect2 = function(selector) {
if (selector == null) {
selector = '.select2';
}
return $(this).select2({
ajax: {
data: function(term, page) {
return {
search: term,
depth: $(this).data('depth')
};
},
results: function(data, page) {
return {
results: data
};
},
url: $(this).data('url')
},
createSearchChoice: function(term, data) {
if ($(data).filter(function() {
return this.title.localeCompare(term) === 0;
}).length === 0) {
return {
id: term,
title: term
};
}
},
createSearchChoicePosition: 'bottom',
formatResult: function(item) {
return item.title;
},
formatSelection: function(item) {
return item.title;
},
initSelection: function(element, callback) {
return callback({
id: $(element).data('id'),
title: $(element).val()
});
}
});
};
Answer the question
In order to leave comments, you need to log in
Now I began to use gem "select2-rails"
There is a presentation on Habrahabr - How we wrapped Select2 into a helper
Very convenient, there is documentation with examples.
The input value must initially contain id. You apparently have Country#to_s and the name is rendered there.
or
= f.input :country, input_html: { value: post.location.country.id }
The answer is:
= 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 } }
initSelection: (element, callback) ->
callback
id: $(element).val(),
title: $(element).data('title')
In vain you use CoffeeScript, so the number of people willing to help you is drastically reduced
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question