我怎样才能得到未选择的选项的值在选择二用select2:unselect
$('#mySelect').on("select2:unselect", function(e){ var unselected_value = $('#mySelect').val(); // using this shows 'null' // or using below expression also shows 'null' var unselected_value = $('#mySelect :selected').val(); alert(unselected_value); }).trigger('change');
在上面的代码警报显示'null'
我需要使用,select2:unselect
因为'change'事件会感觉到:select
并且:unselect
两者兼而有之.
实际上,数据值在事件Object内.如果您正在处理select2多个值,那将非常有用.
function(e){ console.log(e.params.data) }
这是一个较老的问题,但也许这个答案会对某人有所帮助.我正在使用带有多个值/标签的Select2 v4.0.3,并且只需删除特定ID的ID.我真的不想使用unselecting
其他答案中提到的事件.如果unselect
没有args
对象,那么你可以获得你想要删除的那个ID ...
jQuery('.mySelect2').on("select2:unselecting", function(e){ return true; // I don't use this unselecting event but here is how you could use it to get the ID of the one you are trying to remove. console.log(e); console.log(e.params); console.log(e.params.args.data); console.log(e.params.args.data.id); //console.log(e.params.args.data.tag); data.tag is specific to my code. }); jQuery('.mySelect2').on('select2:unselect', function (e) { console.log(e); console.log(e.params); console.log(e.params.data); console.log(e.params.data.id); //console.log(e.params.data.tag); data.tag is specific to my code. /* Now you can do an ajax call or whatever you want for the specific value/tag that you are trying to remove which is: e.params.data.id. */
最后,我得到了解决方案,那就是:unselected选项的值仅在未选择之前可用。没有select2:unselect
,而在select2:unselecting
现在的代码将是:
$('#mySelect').on("select2:unselecting", function(e){ var unselected_value = $('#mySelect').val(); alert(unselected_value); }).trigger('change');