选择下拉列表中的值时,为某些控件添加了默认选项

时间:2012-04-20 08:13:12

标签: javascript knockout.js

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

这是我的淘汰代码:

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很陌生,每个有关工作示例的帮助都会大大减少。谢谢!

1 个答案:

答案 0 :(得分: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);