[英]Select2 change input name if tag is being submited
所以我有以下select2:
productFamilySelect.select2({
tags: true
});
默認情況下,關聯的select元素的名稱為product_family_id
,是否有一種方法可以將輸入的名稱更改為讓我們說product_family_name
,如果用戶輸入了一個選定的值? 這樣,我就可以肯定地在后端區分一個已經存在的值和一個用戶想到的值。 通過數據庫中的id進行檢查並不十分適合,因為該值本身實際上可以是數字。
在深入研究select2自定義事件后,我找到了一種方法:
首先添加createTag回調,如下所示:
productFamilySelect.select2({
tags: true,
createTag: function (params) {
var term = $.trim(params.term);
if (term === '') {
return null;
}
return {
id: term,
text: term,
newTag: true
}
}
});
然后,添加以下偵聽器:
productFamilySelect.on('select2:select', function (e) {
if (e.params.data.newTag === true) {
$(this).attr('name', 'product_family_name');
} else {
$(this).attr('name', 'product_family_id');
}
});
似乎有點駭人聽聞,因為它不在實際的select2配置的配置中,但是它確實可以完成工作:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.