Ale*_*xei 3 javascript multipleselection jquery-select2
我正在使用jQuery select2控件,我需要实现以下功能:如果用户尝试添加某个元素,基于某种算法,我应该从选择中删除另一个(不兼容的)元素.我看到两种方法来实现这一目标:
1)禁止对所选值的自动排序2)获取最后选择的项的值,并且可选地从列表中删除不兼容的项
1)我无法想象如何禁止自动排序("数据"和"值"在执行选择后排序)2)我无法在任何地方找到最后选择的项目信息(我希望在选择中找到一些东西)事件e变量).
我的代码如下:
$("#PhaseFilterSelectedList").select2()
.on("select2:select", function (e) {
// removing option inconsistent with last selected item, if any
var allData = $("#PhaseFilterSelectedList").select2("val");
if (!allData || allData.length < 2)
return;
//alert("Value = " + $("#PhaseFilterSelectedList").select2("val").join(','));
//alert("Data = " + $("#PhaseFilterSelectedList").select2("data")[0].id + " " + $("#PhaseFilterSelectedList").select2("data")[1].id);
var lastItemId = allData.slice(-1)[0];
var lastItemHalf = Math.floor((parseInt(lastItemId) + 1) / 2);
var toRemove = jQuery.grep(allData, function (elem, index) {
return elem != lastItemId && Math.floor((parseInt(elem) + 1) / 2) == lastItemHalf;
});
if (!toRemove || toRemove.length < 1)
return;
allData.splice($.inArray(toRemove[0], allData), 1);
$("#PhaseFilterSelectedList").select2("val", allData);
})
Run Code Online (Sandbox Code Playgroud)
不兼容的元素删除工作正常,但我无法识别用户执行的最后一个选择.
知道如何执行此任务?谢谢.
小智 15
嘿,我可能有点迟到回答这个,但我发现了一个非常简单的解决方案.我们通过查看最后一个选定项目的事件是正确的.这对我有用.
var $eventSelect = $('.select_field'); //select your select2 input
$eventSelect.on('select2:unselect', function(e) {
console.log('unselect');
console.log(e.params.data.id); //This will give you the id of the unselected attribute
console.log(e.params.data.text); //This will give you the text of the unselected text
})
$eventSelect.on('select2:select', function(e) {
console.log('select');
console.log(e.params.data.id); //This will give you the id of the selected attribute
console.log(e.params.data.text); //This will give you the text of the selected
})Run Code Online (Sandbox Code Playgroud)