How to manually add an item into datasource in Kendo UI Combobox

javascript, jquery, kendo-ui

Solution

The problem is that DataSource is initialized asynchronously, I mean, you start loading when the `combobox` is initialized but the operation does not finish until the data is received back from the server. Then, and only then, is when you should invoke that element. Is not even acceptable move the `add` statement to the end of the sample code since loading from a server might take milliseconds or seconds.

If you want to add an element to what is being received from the server, you might use:

$(document).ready(function () {
    //Combobox Init (From Servlet)
    var comboBoxDataSource = new kendo.data.DataSource({
        transport: {
            read: {
                url     : "net/samso/action/common/ComboAction?flag=SRCHGT_IO_GB", // url to remote data source 
                dataType: "json",
                type    : 'GET'
            }
        },
        schema   : {
            model: {
                fields: {
                    key  : { type: "string" },
                    value: { type: "string" }
                }
            },
            data: function(result) {
                //Manually add an item
                result.push({key: "062", value: "Total"});
                return result
            }
        }
    });

    //Initialize Combobox
    $("#cb_srchgt_io_gb").kendoComboBox({
        dataSource    : comboBoxDataSource,
        dataTextField : "value",
        dataValueField: "key"
    })
});

You might do the same thing using `requestEnd` event and pushing the extra element to `e.response`:

requestEnd: function (e) {
    console.log("e", e);
    e.response.push({key: "062", value: "Total"});
}

Basically, any event that is fired after being received the data from the server is fine.

Problem

I have a combobox that is being populated by a JSON string received from the servlet. ``` $(document).ready(function() { //Combobox Init (From Servlet) var comboBoxDataSource = new kendo.data.DataSource({ transport : { read : { url : "net/samso/action/common/ComboAction?flag=SRCHGT_IO_GB", // url to remote data source dataType : "json", type : 'GET' } }, schema : { model : { fields : { key : { type : "string" }, value : { type : "string" } } } } }); //Manually add an item comboBoxDataSource.add({key: "062", value: "Total"}); //Initialize Combobox $("#cb_srchgt_io_gb").kendoComboBox({ dataSource : comboBoxDataSource, dataTextField : "value", dataValueField : "key" }) }); ``` The code works fine until I try to manually add an item to the datasource `comboBoxDataSource.add({key: "062", value: "Total"});`. When the item is added, it gets rid of the other items that was populated from JSON data in the datasource. Why is this happening?

Original source