我需要使用 Select2 构建一个搜索表单,但我无法让它正常工作。
用户在通过 AJAX 填充建议的字段中输入搜索词。单击建议会将他带到页面。否则,他需要单击提交按钮/或按回车键,以进行扩展搜索。最后一点(单击提交按钮)不起作用。
<form action="/search" method="get" class="form-search" id="global_search_form">
<div class="input">
<input type="text" name="q" class="search-query" id="global_search" placeholder="Enter search term ...">
<button type="submit" class="btn">Search</button>
</div>
</form>
<script type="text/javascript">
jQuery("#global_search").select2({
placeholder: "Enter search term ...",
minimumInputLength: 2,
multiple: 1,
containerCssClass: 'search-query',
ajax: {
url: 'remoteGlobalSearch',
dataType: 'jsonp',
quietMillis: 100,
data: function (term, page) {
return {
q: term,
per_page: 10,
page: page
};
},
results: function (data, page) {
var more = (page * 10) < data.total;
return {
results: data.items,
more: more
};
}
},
formatResult: itemFormatResult,
formatSelection: itemFormatSelection,
escapeMarkup: function (m) {
return m;
}
});
function itemFormatResult(item) {
var markup = '<table class="item-result"><tr>';
if (item.image !== undefined) {
markup += '<td class="item-image"><img src="' + item.image + '" /></td>';
}
markup += '<td class="item-info"><div class="item-type">' + item.type_string + '</div>';
markup += '<div class="item-title">' + item.title + '</div>';
markup += '<div class="item-description">' + item.description + '</div>';
markup += '</td></tr></table>';
return markup;
}
function itemFormatSelection(item) {
location.href = item.url;
}
</script>
干杯