如何在输入框上设置默认值,并在其上初始化select2 [英] how to set default value on an input box with select2 initialized on it
问题描述
如何使用select2在输入框上设置默认值?这是我的HTML
How do I set default value on an input box with select2? here is my HTML
<input type="text" id="itemId0" value="Item no. 1">
和我的javascript:
and my javascript:
$("#itemId0").select2({
placeholder: 'Select a product',
formatResult: productFormatResult,
formatSelection: productFormatSelection,
dropdownClass: 'bigdrop',
escapeMarkup: function(m) { return m; },
minimumInputLength:1,
ajax: {
url: '/api/productSearch',
dataType: 'json',
data: function(term, page) {
return {
q: term
};
},
results: function(data, page) {
return {results:data};
}
}
});
function productFormatResult(product) {
var html = "<table><tr>";
html += "<td>";
html += product.itemName ;
html += "</td></tr></table>";
return html;
}
function productFormatSelection(product) {
var selected = "<input type='hidden' name='itemId' value='"+product.id+"'/>";
return selected + product.itemName;
}
这是问题:
如果我不初始化我的输入框进入select2框,我可以显示输入框的默认值,即项目编号1,
但是当我用select2初始化时,例如。 $(#itemId0)。select2({code here});
然后我无法显示我的文本框的默认值。 。
here is the issue:
If I wont initialize my input box into a select2 box, I can display the default value of my input box which is "Item no. 1",
but when I initialize it with select2 eg. $("#itemId0").select2({code here});
I cant then display the default value of my text box. .
任何人都知道如何显示请问默认值?
Anyone knows how can I display the default value please?
推荐答案
您需要使用 initSelection
方法作为在Select2的文档中描述。
You need to utilize the initSelection
method as described in Select2's documentation.
来自文档:
创建Select2时调用,以允许用户根据元素select2的值附加初始化选择。
Called when Select2 is created to allow the user to initialize the selection based on the value of the element select2 is attached to.
在您的情况下,请查看加载远程数据示例,因为它显示了如何将其与AJAX请求合并。
In your case, take a look at the Loading Remote Data example as it shows how to incorporate it along with AJAX requests.
我希望这会有所帮助。
这篇关于如何在输入框上设置默认值,并在其上初始化select2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!