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

喜欢而已 提交于 2019-12-08 05:20:59

问题


I have this fiddle which is an extension of the Backbone/Marionette playground fiddle. I included select2 js and css files.

Is it possible to edit a tag that is not the last tag? You can edit by backspacing in the box, but it only lets you touch the last one. I would like it to act like a gmail 'to' list where you can double click on one and edit it, then it goes back to a tag on blur.

        this.$('#foo').select2({
            data: [{
                id: 1,
                text: "test1.com"
            }, {
                id: 2,
                text: "test2.com"
            }],
            multiple: true,
            allowclear: true,
            tags: [],
            placeHolder: "Click Here!",
            tokenSeparators: [',', ' '],
            minimumResultsForSearch: 1
        });

回答1:


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.



来源:https://stackoverflow.com/questions/33130028/backbone-marionette-with-select2-v4-0-editing-the-tags

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