In Select2, how do formatSelection and formatResult work?

孤人 提交于 2019-12-06 05:39:36

问题


I'm using Select2 (http://ivaynberg.github.io/select2/) to have an input field of a form (let's say its id is topics) to be in tagging mode, with the list of existing tags (allowing the user to choose some of these tags, or to create new ones) being provided by an array of remote data.

The array (list.json) is correctly got from my server. It has id and text fields, since Select2 seems to need these fields. It thus looks like this:

[ { id: 'tag1', text: 'tag1' }, { id: 'tag2', text: 'tag2' }, { id: 'tag3', text: 'tag3' } ]

The script in the HTML file looks like this:

$("#topics").select2({
    ajax: { 
        url: "/mypath/list.json",
        dataType: 'json',
        results: function (data, page) { 
        return {results: data};
        },   
    }
});

But the input field is showing "searching", which means it's not able to use the array for tagging support.

In the script with Select2, I know I have to define formatSelection and formatInput, but I'm not getting how they should work in my case, although I have read the Select2 documentation... Thank you for your help!


回答1:


You need to add the function like explained here. In your example:

function format(state) {

    return state.text;
}


来源:https://stackoverflow.com/questions/23643409/in-select2-how-do-formatselection-and-formatresult-work

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