使用Knockout从Select中预填充文本输入

Prepopulate Text Input From Select Using Knockout

本文关键字:填充 文本 输入 Knockout Select 使用      更新时间:2023-09-26

我正在使用Knockout,并使用值预填充选择列表。我希望这些值被复制到一个文本框,但对于用户能够覆盖任何是在文本框。当前,当文本框失去焦点时,它的值将恢复到当前下拉列表的选定值。

ViewModel:

function ViewModel() {
var self = this;
self.services = ['/api/trainers', '/api/trainingcategories']
self.selectedApi = ko.observable('/api/trainers');
}
HTML:

<div class="form-group">
<label>API</label>
<select data-bind="options: services,
        optionsCaption: 'Choose an API...',
        value: selectedApi,
        valueAllowUnset: true"></select>
</div>
<div class="form-group">
    <input class="form-control" type="text" data-bind="value: selectedApi" />
    <button type="submit" class="btn btn-default">Call API</button>
</div>

我认为设置valueAllowUnset会有空白的选择元素的效果,每当selectedApi值被设置为某些东西,不是在选项列表中,但这不是我看到的行为。

在Knockout的3.1.0版本中添加了valueAllowUnset选项。