haml:
.form-group
= f.hidden_field :gender, :id => 'select2', :style => "width:100%; height: 40px"
JS:
$("#select2").select2({
createSearchChoice: function (term, data) {
if ($(data).filter(function () {
return this.text.localeCompare(term) === this.text;
}).length === 0) {
return {
id: term,
text: term
};
}
console.log('SELECT2', $("#select2").data.text);
},
placeholder: "Enter custom gender or select one below",
multiple: false,
data: [{
id: 'male',
text: 'male'
}, {
id: 'female',
text: 'female'
}, {
id: 'custom',
text: 'custom'
}]
});
select2正在做我现在需要的一切,但是占位符并未在我看来。任何帮助,非常感谢。
我为此写了一个小咖啡脚本,它可以完成所有正常的自动填充物以及预填充的数据
$(document).ready ->
$('.select2').each (i, e) =>
select = $(e)
options =
placeholder: select.data('placeholder')
minimumInputLength: 1
if select.hasClass('ajax') # only add ajax functionality if this class is present
options.ajax =
url: select.data('source')
quietMillis: 100
dataType: 'json'
data: (term) ->
q: term
results: (data) ->
results: data.resources
more: false
options.dropdownCssClass = "bigdrop"
options.initSelection = (element, callback) ->
callback({ text: element.attr('data-value') })
select.select2(options)
我隐藏的字段就像这个
hidden_field_tag(:search, '', id: 'res_select', class: 'select2 ajax form-control select-overide', style: 'width: 100%;', data: { source: "/products/autocomplete", placeholder: 'Search for a name' }, :value=> params["search"], "data-value" => params['search'])
尝试一下它将起作用。
这是上面的一个很好的答案。我通过准备一个空白的初始选项来较少的代码解决,占位符填写:
$('.compare-search').prepend('<option/>').val(function(){return $('[selected]',this).val() ;});