[英]Display Select2 value not in list
盡管可以使用createSearchChoice將新值添加到Select2(3.5)元素中,但是如果列表中未包含新值,如何顯示呢? 我可以添加不在Select2列表中的值,但是如何顯示不在列表中的默認值?
$("#select").select2({
placeholder: "Who is the invoice from?",
minimumInputLength: 2,
quietMillis: 300,
allowClear : true,
ajax: {
url: "accountsDataStore.xsp",
dataType: 'json',
data: function (term, page) {
return {
q: term, // search term
page_limit: 10
};
},
results: function (data, page) { return data; }
},
// extra code to allow entering value not in list
id: function(object) { return object.text; },
//Allow manually entered text in drop down.
createSearchChoice:function(term, data) {
if ( $(data).filter( function() {
return this.text.localeCompare(term)===0;
}).length===0) {
return {id:term, text:term};
}
},
initSelection: function(element, callback) {
//sets a default value (if a value was selected previously)
//get the existing value
var id = $(element).val();
//if a value was selected: perform an Ajax call to retrieve the text label
if (id !== "") {
$.ajax(
"accountsDataStore.xsp", {
data: { id: id },
dataType: "json"
}).done(function(data) {
// ** TODO if value not found, display current element value -- HOW?? **
callback(data); });
}
}
}).on('change', function (evt) {
// Do something after value changes
}
);
在initSelection
期間,如果找不到默認值,那么如何顯示當前值?
<input type="hidden"
id="view:_id1:_id4:callback1:inputName"
name="view:_id1:_id4:callback1:inputName"
aria-required="true"
value="ACME Company"
tabindex="-1"
class="select2-offscreen">
在表單中,該值已設置,只是不顯示在顯示所選值的<span>
中。 我們是否只是以某種方式將其添加到列表中?
謝謝。
我個人通過適當使用視圖控制器(viewScoped bean)來處理允許值不在列表中的select2元素。
使用以下代碼,我可以做三件事:
<xp:comboBox id="comboDemo" value="#{ctrl.comboValue}" validator="#{ctrl.validateCombo}">
<xp:selectItems value="#{ctrl.comboChoices}" />
</xp:comboBox>
除非默認值為null
,否則將考慮當前綁定值來構建默認選項。
public List<SelectItem> getComboChoices() {
if (comboChoices == null) {
comboChoices = new ArrayList<SelectItem>();
// Complete with your own logic here
if (StringUtil.isNotEmpty(comboValue)) {
comboChoices.add(new SelectItem(comboValue, comboValue));
}
}
return comboChoices;
}
一旦選擇了新值,我需要確保它將以返回服務器的方式被接受。 我利用驗證階段潛入新的價值。
public void validateCombo(FacesContext facesContext, UIComponent component, Object value) {
boolean isNewValue = true;
for (SelectItem item : comboChoices) {
if (value.equals(item.getValue())) {
isNewValue = false;
break;
}
}
if (isNewValue) {
String newValue = (String) value;
comboChoices.add(new SelectItem(newValue, newValue));
}
}
以上是我所做工作的簡明版本。 您可以使它更聰明,但我希望示例足夠清楚。
動態選項創建
除了預填充的選項菜單外,Select2還可以根據用戶在搜索框中輸入的文本動態創建新選項。 此功能稱為“標記”。 要啟用標記,請將標記選項設置為true:
在這里查看詳細信息
在select2中,您打算做的事情稱為標記,這就是它的進行方式;
<select class="form-control">
<option selected="selected">orange</option>
<option>white</option>
<option>purple</option>
</select>
//the major ish
$(".js-example-tags").select2({
tags: true
});
用簡單的英語只需在select2初始化期間設置標簽,您就可以選擇添加一個不在下拉列表中的值。
希望這對您有所幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.