如何使用knockout.js根据现有数组中select元素的选定值设置输入字段的可见性

时间:2013-05-31 20:03:41

标签: javascript knockout.js

我正在创建一个动态过滤器列表,允许用户添加多个条件。该列表由select元素和两个输入字段组成。最初只显示一个字段。第二个字段只应在选择BETWEEN值时显示。我已经看到了使用select元素设置元素可见性的示例。 以下是我到目前为止的情况:

JS

function FilterList(Operator, FilterCriteria, FilterCriteriaRange) {
    var self = this;
    self.operator = ko.observable(Operator);
    self.criteria1 = ko.observable(FilterCriteria);
    self.criteria2 = ko.observable(FilterCriteriaRange);
}

function AppViewModel() {
    var self = this;

    self.filterOperators = ko.observableArray([{
        operatorName: "EQUALS",  operatorValue: "=" }, {
        operatorName: "GREATER THAN", operatorValue: ">"}, {
        operatorName: "GREATER THAN OR EQUAL TO", operatorValue: ">="}, {
        operatorName: "LESS THAN", operatorValue: "<" }, {
        operatorName: "LESS THAN OR EQUAL TO", operatorValue: "<=" }, {
        operatorName: "NOT EQUAL TO", operatorValue: "<>" }, {
        operatorName: "NOT LESS THAN", operatorValue: "!>" }, {
        operatorName: "NOT GREATER THAN", operatorValue: "!<" }, {
        operatorName: "BETWEEN", operatorValue: "BETWEEN" }, {
        operatorName: "LIKE",  operatorValue: "LIKE"
    }]);
    //define filter collection
    self.myfilters = ko.observableArray([]);
    self.addFilter = function () {
        self.myfilters.push(new FilterList(self.filterOperators[0]));
    };

    self.inputVisible = ko.computed(function(){
        //retrieve the selected value of the current row and display the second criteria field if the selected value is BETWEEN
        //return self.operator();
    });
}
ko.applyBindings(new AppViewModel());

HTML

<input type="button" value="Add Filter" title="Add Group" data-bind="click: $root.addFilter" />
<table>
   <tbody data-bind="foreach: myfilters">
     <tr>
     <td>
       <select data-bind="options: $root.filterOperators, value:operator, optionsText:'operatorName'"></select>
     </td>
     <td>
       <input data-bind="value: criteria1" />
      </td>
     <td>
      <input data-bind="value: criteria2, visible: inputVisible() === 'BETWEEN'" />
     </td>
    </tr>
    </tbody>
</table>

我遇到的问题是获取我正在与之交互的当前行的正确值。此链接http://jsfiddle.net/rlcrews/R6Kcu/提供了一个工作小提示,显示正在生成的行我只是坚持如何从选定行中派生所选值。

1 个答案:

答案 0 :(得分:1)

这是你要找的吗? http://jsfiddle.net/pyvJW/1/

由于您正在遍历myfilters,因此您可以访问operator字段。由于运算符是可观察的,因此您只需要括号来访问operatorName。

<input data-bind="value: criteria2, visible: operator().operatorName === 'BETWEEN'" />