How do I clear / reset a Kendo DropDownList with only javascript?

Josh picture Josh · Sep 8, 2013 · Viewed 21.8k times · Source

I have a Kendo DropDownList (name=Function) that contains 3 options. When one option is selected, it triggers an ajax call to get data to populate a different DropDownList (name=Parents). This works as-expected. However, if the user then changes the original DropDownList "Function" back to a different selection, I need to clear/reset (remove all options) and disable the "Parents" DropDownList.

function LoadKendoDropdownContents(dropdownBoxId, data) {
  var dropdownBox = $("#" + dropdownBoxId).data("kendoDropDownList");

  if (data === "" || data === null || $.isEmptyObject(data)) {
    var dataSource = [];
  }
  else {    
    var dataSource = data;
  }

  dropdownBox.setDataSource(dataSource);
}

It's really the "var dataSource = []" that is giving me problems. It's like the "Parents" DropDownList isn't refreshing/rebinding when that is applied. All of the options except the one that was selected get removed, but how do I remove the one that was previously selected? I want it to be "empty" again.

Thank you.

---- Solution I used ----

function LoadKendoDropdownContents(dropdownBoxId, data) {
  var dropdownBox = $("#" + dropdownBoxId).data("kendoDropDownList");

  if (data === "" || data === null || $.isEmptyObject(data)) {
    var dataSource = new kendo.data.DataSource({
      data: []
    });

    dropdownBox.text(" --- ");
    dropdownBox.value(-1);
  }
  else {
    var dataSource = new kendo.data.DataSource({
      data: data
    });

    dropdownBox.text("[Select]");
    dropdownBox.value(-1);
  }

  dropdownBox.setDataSource(dataSource);
}

Answer

CodingWithSpike picture CodingWithSpike · Sep 9, 2013

It might be easier to use the cascading dropdown feature.

When you change the dataSource, it removes the dropdown items, but you also need to clear the selected text and disable the box, by calling:

dropdownBox.setDataSource(dataSource);
dropdownBox.text('');
dropdownBox.enable(false);