select2: “text is undefined” when getting json using ajax

后端 未结 2 1582
轮回少年
轮回少年 2021-01-22 09:13

I\'m having an issue when getting json results back to select2. My json does not return a result that has a \"text\" field so need to format the result so that select2 accepts \

相关标签:
2条回答
  • 2021-01-22 09:26

    note that select2 is always in {id,text} pair so you need to specify both

    results: function (data, page) {
                var newData = [];
                _.each(data, function (item) {
                    newData.push({
                        id: item.Id  //id part present in data 
                      , text: item.DisplayString  //string to be displayed
                    });
                });
                return { results: newData };
            }
        },
    
    0 讨论(0)
  • 2021-01-22 09:50

    Thanks to @neel shah for solving my problem. i had just little problem, i didnt wanted to use extra library so thats why i changed to normal jquery. so if wanna go for normal jquery or javascript.

    results: function (data, page) {
     var newData = [];
        $.each(data, function (index,value) {
            newData.push({
                id: value.Id,  //id part present in data
                text: value.DisplayString  //string to be displayed
            });
        });
    }
    

    OR

    results: function (data, page) {
       var newData = [];
        for ( var i = 0; i < data.length; i++ ) {
            newData.push({
                id: data[i].Id,  //id part present in data
                text: data[i].DisplayString  //string to be displayed
            });
    }
    

    All credits go to neel shah. Thanks again.

    0 讨论(0)
提交回复
热议问题