0

我有两个下拉列表和一个输入框。当从下拉列表中选择一个值时,应在其他两个控件中预先选择一个特定值。

这是我的淘汰赛代码:

var viewModel = {
    templates: ko.observableArray(["Template1", "Template2"]),
    //when Template2 is selected Spanish should be preselected from the languages select list and name of the template should be written in the folderName inputbox (Template2)
    //when Template1 is selected French should be preselected and name of the template should be written in the folderName inputbox (Template1)
    languages: ko.observableArray(["English", "Spanish", "French"]),
    folderName: ko.observable()
}

ko.applyBindings(viewModel);

这是我的示例 html 代码:

<select id="templates" data-bind="options: templates"></select>

<div>
<input data-bind="value: folderName"/>
</div>

<div>
<select id="languages" data-bind="options: languages"></select>
</div>  

选择 Template2 时,应从语言选择列表中预先选择西班牙语,并且应将模板名称写入 folderName 输入框 (Template2)。选择 Template1 时,应预先选择法语,并将模板名称写入 folderName 输入框(Template1)

小提琴:http: //jsfiddle.net/PsyComa/Q8unN/19/

我对javascript相当陌生,对工作示例的每一个帮助都会非常感激。谢谢你!

4

1 回答 1

0

这是更通用的代码。如果您templateLanguageMap使用模板语言对填充,此代码将解决您的问题。你不必写很多if语句。祝你好运!

<select id="templates" data-bind="options: templates"
    onchange="onTemplateChange(value);"></select>

<div>
<input id="folderName"  data-bind="value: folderName"/>
</div>

<div>
<select id="languages" data-bind="options: languages"></select>
</div>

JavaScript:

    var viewModel = {
        templates: ko.observableArray(["Template1", "Template2"]),
        //when Template2 is selected Spanish should be preselected from the languages select list and name of the template should be written in the folderName inputbox (Template2)
        //when Template1 is selected French should be preselected and name of the template should be written in the folderName inputbox (Template1)
        languages: ko.observableArray(["English", "Spanish", "French"]),
        folderName: ko.observable()
    }

    var selectTemplates = document.getElementById('templates');
    var selectLanguages = document.getElementById('languages');
    var inputFolderName = document.getElementById('folderName');

    var templateLanguageMap = {"Template1":"Spanish", "Template2":"French"};

    onTemplateChange = function(value){
        inputFolderName.value = value;
        for ( var i = 0; i < selectLanguages.options.length; i++ ) {
            if ( selectLanguages.options[i].value == templateLanguageMap[value]) {
                selectLanguages.options[i].selected = true;
                return;
            }
        }
    }

    ko.applyBindings(viewModel);
    onTemplateChange(selectTemplates.value);
于 2012-04-20T09:23:14.217 回答