我如何触发一个新的阿贾克斯选择2新/删除标签事件? [英] How do I fire a new ajax on select2 new /remove tag event?
问题描述
我用下面的代码片段与阿贾克斯远程添加新的选择2 标记,我要注册或删除我很多的一些记录到许多台新的标签/删除标签事件
I use the following snippet to add a new select2 tag remotely with ajax and I want to register or remove some records of my many to many table on new tag / remove tag event
表看起来像
---------------------------------
+--voucher_id--+|+--product_id--+
---------------------------------
+ 123 | 566 +
---------------------------------
+ 156 | 566 +
---------------------------------
+ 123 | 426 +
---------------------------------
+ 156 | 516 +
---------------------------------
我的JavaScript
My Javascript
$(".e6").select2({
tags: true,
placeholder: 'placeholder',
minimumInputLength: 1,
ajax: {
url: 'searchProducts',
dataType: 'json',
data: function(term) {
return {q: term};
},
results: function(data) {
return {results: data};
}
},
createSearchChoice: function(term, data) {
if ($(data).filter(function() {
return this.computername.localeCompare(term) === 0;
}).length === 0) {
return {id: term, name: term};
}
},
formatResult: function(item, page) {
return item.computername;
},
formatSelection: function(item, page) {
return item.computername;
}
});
在返回的JSON我有一个产品ID,以及和我在寻找一种方式来开火选择2事件一个新的Ajax,但我想不通的地方应该怎样做才能从我的表保存或删除数据。
In the returned json I have a product ID as well and I'm searching a way to fire a new ajax on select2 event but I can't figure out where should be done to save or remove data from my table.
做一些研究,我已经能够建造这将更新记录在桌子上,上面还有一个功能,这是工作的好SOFAR
Making some researches I've been able to build a function which would update records on the table above and which is working good sofar
$('.e6').on("change", function(e){
console.log(ids);
console.log(gs);
$.ajax({
type: "POST",
url: '/admin/?controller=vouchers&action=updateRelatedProducts',
data: {ids: ids, gs:gs},
error: function () {
alert("error");
}
});
});
不过,我有问题来填充我的初始存在的标签输入字段
But I have problems to populate my input field with initial existing tags
推荐答案
未经测试,但应该工作:
Not tested but should work :
$('.e6').on("change", function(e){
if (e.removed) {
$.ajax({
type: "POST",
url: '/admin/?controller=vouchers&action=updateRelatedProducts',
data: {id: e.removed.id, action: remove}, //Or you can e.removed.text
error: function () {
alert("error");
}
});
}
if (e.added) {
$.ajax({
type: "POST",
url: '/admin/?controller=vouchers&action=updateRelatedProducts',
data: {id: e.added.id, action: add}, //Or you can e.added.text
error: function () {
alert("error");
}
});
}
//OR you can play with val data instead
if (e.val) {
$.ajax({
type: "POST",
url: '/admin/?controller=vouchers&action=updateRelatedProducts',
data: {val: JSON.stringify(e.val)}, //Will send all the selected values
error: function () {
alert("error");
}
});
}
}
这篇关于我如何触发一个新的阿贾克斯选择2新/删除标签事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!