Backbone/Marionette with select2 v4.0, editing the tags

十年热恋 提交于 2019-12-06 15:52:28

Unfortunately, there is no way to do this using just the select2 out-of-the-box functionality. But it's quite extendable, so here's what does the trick:

var $select2 = this.$('#foo').select2({ tags: true });

var select2 = $select2.data("select2");            
$(document.body).on("dblclick", ".select2-selection__choice", function(event) {
    var $target = $(event.target);

    // get the text and id of the clicked value
    var targetData = $target.data("data");
    var clickedValue = targetData.text;
    var clickedValueId = targetData.id;

    // remove that value from select2 selection
    var newValue = $.grep(select2.val(), function (value) {
        return value !== clickedValueId;
    });
    $select2.val(newValue).trigger("change");

    // set the currently entered text to equal the clicked value
    select2.$container.find(".select2-search__field").val(clickedValue).trigger("input").focus();
});

And a JsFiddle, of course.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!