これらは、この問題を解決するために選択したプラグイン(jqueryバージョン)に加えた変更の完全なセットです。
Chosen.prototype.choice_build = function(item) {
this.new_term_to_be_added = null;
// ....
};
Chosen.prototype.no_results = function(terms) {
// ....
no_results_html.find("span").first().html(terms);
this.new_term_to_be_added = terms;
return this.search_results.append(no_results_html);
};
Chosen.prototype.keydown_checker = function(evt) {
// ...
case 13:
if(this.new_term_to_be_added != null && this.options.addNewElementCallback != null) {
var newElement = this.options.addNewElementCallback(this.new_term_to_be_added);
if(newElement!=null && newElement.length == 1) {
// KEY TO SOLVING THIS PROBLEM
this.result_highlight = newElement;
// This will automatically trigger the change/select events also.
// Nothing more required.
this.result_select(evt);
}
this.new_term_to_be_added = null;
}
evt.preventDefault();
break;
// ...
};
this.new_term_to_be_addedは、事前定義されたオプションに含まれていない、現在入力されている文字列を維持します。
options.addNewElementCallbackは、呼び出し元の関数へのコールバックであり、呼び出し元の関数が処理(サーバーなどに送信)できるようにするためのものであり、同期している必要があります。以下はスケルトンです:
var addTagCallback = function(tagText) {
var newElement = null;
$.ajax({url : that.actionUrl,
async : false,
dataType: "json",
data : { // ....},
success : function(response) {
if(response) {
$('#tagSelection').append(
$('<option></option>')
.val(data.Item.Id)
.html(data.Item.Value)
.attr("selected", "selected"));
$("#tagSelection").trigger("liszt:updated");
// Get the element - will necessarily be the last element - so the following selector will work
newElement = $("#tagSelection_chzn li#tagSelection_chzn_o_" + ($("#tagSelection option").length - 1));
} else {
// Handle Error
}
}});
return newElement;
};
newElementはjquery要素です。オプションのリストに最後に追加されたliオブジェクトです。
this.result_highlight=newElement;を実行することによって およびthis.result_select(evt); 選択したプラグインにこれを選択するように指示します。これは、単一選択でも複数選択でも機能します。Rifkyのソリューションは、単一選択に対してのみ機能します。