简体   繁体   中英

How to force selecting first item when using Kendo MVVM Dropdownlist

function GenericSelectFirst(e){
  // This function is called without any errors, I have verified it
  e.sender.select(0);
}

<select class="full-width"

        name="..."
        data-bind="source: ..., value: ..., visible: ..., events:{dataBound: Function.GenericSelectFirst}"
        data-role="dropdownlist"
        data-value-field="..."
        data-text-field="..."
        data-value-primitive="true"
        data-auto-bind="true"
        required="required"
>
</select>

I did not think that it is that hard to achieve such a common easy scenario, but I have a Kendo DropDownList which initialize using MVVM style, and it is binding a remote datasource.

What I want to achieve is that, once the remote datasource is ready and bound to the widget, the first option is selected by default (and of course the value of the first item should be bound to the view model)

I tried to do it directly with the above code, which binds an dataBound event to the widget, and select the first item when it fires. The callback method has been called without errors, but the widget never select the first option but keep selecting the first default "empty" option.

What did I do wrong and how can I fix it? Any advice is appreciated!

Wich Kendo version are you using? If latest, remember that since V. Q1 2015 , In order to match the Html Select behavior better and solve some issues related to MVVM value binding, the dropdownlist now allows to clear its value (deselect the selected item). This will introduce the following breaking changes:

The widget will not select the first item, when its selected index is -1 The widget will not select the first item, when the selected value is not present in the data source .

Long story short, If someone wants to get the previous behavior, then he/she will need to select first item manually:

  dataBound: function() {
    if (this.select() === -1) { //check whether any item is selected
      this.select(0);
      this.trigger("change");
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM