0
雖然可以使用createSearchChoice將新值添加到Select2(3.5)元素,但如果它不在列表中,如何獲得顯示的新值?我可以在Select2列表中不添加值,但是如何顯示不在列表中的默認值?顯示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>
顯示。我們只是以某種方式將它添加到列表中?
謝謝。