[英]dynamically add new option in jquery chosen plugin where select multiple
[英]Jquery Chosen plugin. Select multiple of the same option
我正在使用選擇的插件來構建多個選擇輸入字段。 在此處查看示例: http : //harvesthq.github.io/chosen/#multiple-select
如果已經選擇了默認行為,則禁用該選項。 在上面的示例中,如果您選擇“阿富汗”,則其在下拉菜單中將顯示為灰色,從而使您無法再次選擇它。
我需要能夠多次選擇同一選項。 我可以添加插件或手動替代中的任何設置嗎?
我創建了selected的版本,該版本允許您多次選擇同一項目,甚至將這些多個條目作為POST變量發送到服務器。 這是您可以執行的操作(我認為這很容易):
(提示:在selected.jquery.js中使用搜索功能查找這些行)
更改:
this.is_multiple = this.form_field.multiple;
至:
this.is_multiple = this.form_field.multiple;
this.allows_duplicates = this.options.allow_duplicates;
更改:
classes.push("result-selected");
至:
if (this.allows_duplicates) {
classes.push("active-result");
} else {
classes.push("result-selected");
}
更改:
this.form_field.options[item.options_index].selected = true;
至:
if (this.allows_duplicates && this.form_field.options[item.options_index].selected == true) {
$('<input>').attr({type:'hidden',name:this.form_field.name,value:this.form_field.options[item.options_index].value}).appendTo($(this.form_field).parent());
} else {
this.form_field.options[item.options_index].selected = true;
}
然后,在調用allows_duplicates
chosen()
,請確保包括allows_duplicates
選項:
$("mySelect").chosen({allow_duplicates: true})
要解決此問題,請在每個選擇中(在select事件中)或在彈出窗口打開時使用以下代碼:
$(".chosen-results .result-selected").addClass("active-result").removeClass("result-selected");
上面的代碼刪除了結果選擇的類,並在li項上添加了active-result類。 因此,每個選定的項目都被視為活動結果,現在您可以再次選擇該項目。
@adam的答案運行得很好,但沒有涵蓋有人要刪除某些選項的情況。
因此,要具有此功能以及亞當的調整,您還需要在以下位置添加此代碼:
Chosen.prototype.result_deselect = function (pos) {
var result_data;
result_data = this.results_data[pos];
// If config duplicates is enabled
if (this.allows_duplicates) {
//find fields name
var $nameField = $(this.form_field).attr('name');
// search for hidden input with same name and value of the one we are trying to delete
var $duplicateVals = $('input[type="hidden"][name="' + $nameField + '"][value="' + this.form_field.options[result_data.options_index].value + '"]');
//if we find one. we delete it and stop the rest of the function
if ($duplicateVals.length > 0) {
$duplicateVals[0].remove();
return true;
}
}
....
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.