我在select2上实施了this jsfiddle。它可以搜索Github repo并返回结果,以便用户可以选择它们。如果只有1个回购匹配给定的搜索,则会自动选择它。
我需要能够使用一些默认选项预填充我的select2表单。如the docs中所述,我应该能够做到这样的事情:
<select id='select2_element' multiple='multiple' style='width:100%;'>
<option value="easypr-ja" selected="selected">EasyPR-Java 70 32393764</option>
</select>
当我按下console.log all selected data
按钮时,我可以看到我预先填好的回购邮件的id
和text
是可访问的,但在浏览器中,上面预先填充的选项会获得显示为undefined undefined easypr-ja
。
为了正确显示默认选项的值,我需要做什么?
我的实现正在进行一些自定义格式化,如下所示:
var createRepo, formatRepo, formatRepoSelection, selectRepos;
formatRepoSelection = function(element) {
return element.name + ' ' + element.forks + ' ' + element.id;
};
formatRepo = function(element) {
var markup;
if (!element.loading) {
return markup = element.name + ' ' + element.id;
}
};
createRepo = function() {
$(".btn-create-repos").off("click");
return $(".btn-create-repos").click(function(e) {
var el, element_ids;
el = $(e.currentTarget);
element_ids = $("#select2_element").select2('data');
return console.log(element_ids);
});
};
selectRepos = function() {
var option, select2_element;
select2_element = $('#select2_element');
select2_element.select2({
placeholder: "Type in 'easypr-ja' to get only 1 result",
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term,
page: params.page
};
},
processResults: function (data, params) {
if (data.items.length === 1) {
setTimeout(function() {
$("#select2-select2_element-results li:first-child").trigger('mouseup');
}, 0);
return {
results: data.items
};
} else {
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
}
},
cache: true
},
escapeMarkup: function(markup) {
return markup;
},
minimumInputLength: 2,
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
};
$(function() {
selectRepos();
return createRepo();
});
答案 0 :(得分:0)
请使用form_for按照以下示例,它可能会有所帮助
<%= f.select(:categories, Category.all.collect {|c| [c.name, c.id]}, {}, id: "event_categories", :multiple => true) %>
<script type="text/javascript">
$("#event_categories").select2();
<% if @event.id.present?%>
$("#event_categories").val(<%= @event.categories.collect(&:id)%>).change()
<% elsif params[:action]=="create" || params[:action]=="update" %>
$("#event_categories").val(<%=params[:event][:categories].map(&:to_i).drop(1)%>).change()
<% end %>
</script>