Select2.js: why is id the same as text on change for removed?

戏子无情 提交于 2019-12-06 12:28:17

There was an issue with your select2 declaration and syntax.

Further more, if you entered any other text, say "eas" or "test", your piece of code reflected that as it is. Check this scenario.

Updated fiddle: http://jsfiddle.net/ZBf5H/

To be specific, you did not give appropriate mapping to your tags. Please find how to access remote data in select 2 from here

The change of code is as below:

$(document).ready(function() {

 var data=[{id:1354,text:'north',restricted:false}, 
           {id:1356,text:'east',restricted:false},
           {id:1357,text:'west',restricted:false},
           {id:1355,text:'south',restricted:false}];

           function format(item) 
              { return item.text; }

        $('#mytags').select2({
            placeholder: 'Search',
            allowClear: true,
            minimumInputLength: 2,
            multiple: true,
            tags: tags,
            tokenSeparators: [','],
            data:{ results: data, text: 'text' },
            formatSelection: format,
            formatResult: format
        });

Let me know if this works for you.

Ok... I've got a working solution, but I still don't exactly understand the difference between select2's tags and data options....

JSfiddle: http://jsfiddle.net/7e8Pa/

I'm initializing select2 with a list of all possible tags via the data option from an array, then selecting those for preloading: the initSelection function checks for ids in the and looks them up in the data array (the pre-stored one, not Select2's). Last, new tags may be added (the createSearchChoice does this). To hook this to my server, I'm just going to insert ajax calls where noted below in the on-change event handler (which gets called after createSearchChoice, and can overwrite the field values for the new object set in createSearchChoice).

JS:

function findWithAttr(array, attr, value) {
    for (var i = 0; i < array.length; i += 1) {
        if (array[i][attr] == value) {
            return array[i];
        }
    }
}



$(document).ready(function () {


    function format(item) {
        return item.text;
    }




    $('#mytags').select2({
        placeholder: 'Search',
        minimumInputLength: 2,
        multiple: true,
        //tags: tags,
        tokenSeparators: [','],

        data: {
            results: tags,
            text: 'text'
        },
        initSelection: function (element, callback) {


            var data = [];
            $($('#mytags').val().split(",")).each(function (i) {


                var o = findWithAttr(tags, 'id', this);

                if (o) {
                    data.push({
                        id: o.id,
                        text: o.text
                    });
                } else {
                    console.log("findWithAttr returned none; likely invalid id");
                }
            });
            console.log("data = " + JSON.stringify(data));
            callback(data);
        },
        createSearchChoice: function (term, data) {
            console.log("create");
            if ($(data).filter(function () {
                return this.text.localeCompare(term) === 0;
            }).length === 0) {
                // call $.post() to add this term to the server, receive back id
                // return {id:id, text:term}
                // or detect this shiftiness and do it below in the on-change

                return {
                    id: -1,
                    text: term
                };
            }
        },

        formatSelection: format,
        formatResult: format
    });



    $('#mytags').on("change", function (e) {
        console.log("change " + JSON.stringify({
            val: e.val,
            added: e.added,
            removed: e.removed
        }));

        if (e.added) {
            alert('added: ' + e.added.text + ' id ' + e.added.id);
            //modifying the id here overrides what is assigned above in createSelection
            e.added.id = 5;
        } else if (e.removed) {
            alert('removed: ' + e.removed.text + ' id ' + e.removed.id);

        }
        var selections = (JSON.stringify($('#mytags').select2('data')));
        $('#selectedText').text(selections);

    });

});

HTML:

<script>
    var tags = [{
        "id": 1354,
            "text": "north",

            "restricted": false
    }, {
        "id": 1355,
            "text": "south",

            "restricted": false
    }, {
        "id": 1356,
            "text": "east",

            "restricted": false
    }, {
        "id": 1357,
            "text": "west",

            "restricted": false
    }];
</script>
<p>tags:
    <input type="text" id="mytags" value="1355" style="width:80%" />
</p>
<p>Selected Options: <span id="selectedText"></span>

</p>
<p>Debug: <span id="debug"></span>

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