knockoutjs foreach n行检查下拉列表是否有价值

时间:2016-01-18 20:11:32

标签: javascript jquery knockout.js knockout-2.0 knockout-mvc

我有这个HTML标记:

<!-- ko foreach: Orders -->
  <div class="row">
    <div>
      <select class="form-control"  data-bind="attr: { id: 'prefix_' + $index() }, options: TeacherNames, optionsValue: 'TeacherId', optionsText: 'TeacherName', optionsCaption: 'Choose Teacher', event: { change: $root.teacherChanged }">
      </select>
    </div>
    <div>
      <a href='#' data-bind="click: $root.RequestImage" class="green-btn blue pull-right">
        <span class="glyphicon glyphicon-cloud-download"></span> Download 
      </a>
    </div>
  </div>
<!-- /ko -->

foreach循环中将有n个项目,在开发时不会知道。

我想要做的是当点击$ root.RequestImage时,代码需要检查是否在该行的受尊重下拉列表中做出选择,如果进行了选择则继续进行,否则显示警告框&#39;错误&#39;消息。

因此在RequestImage中应该执行操作,这是当前的RequestImage函数:

self.RequestImage = function () {

};

任何建议我如何实现这一目标?

谢谢,Laziale

更新:

OrdersVM:

var self = this;
self.Orders = ko.observableArray([]);

$.ajax({
  type: "POST", url: "/webservices/InfoWS.asmx/GetOrders",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function (data) {
    if (data.d != null) {
      var orderIds = [];
      ko.utils.arrayForEach(data.d, function (item) {

        item._teacherOrders = ko.observable();

        $.ajax({
          type: "POST",
          url: "/webservices/InfoWS.asmx/GetTeachersForMyAccount",
          contentType: "application/json; charset=utf-8",
          data: "{'orderId': " + JSON.stringify(item.OrderId) + "}",
          dataType: "json",
          success: function (data) {
            if (data) {
              return item._teacherOrders(data.d);
            }
          },
          error: function (n) {
            alert('Error retrieving teachers for orders, please try again.');
          }
        });

        item.TeacherNames = ko.computed(function () {
          return item._teacherOrders();
        });

        self.Orders.push(item);
        orderIds.push(item.OrderId);

      });
    }
  },
  error: function (data) {
    var response = JSON.parse(data.responseText);
    console.log("error retrieving orders:" + response.Message);
  }
});

1 个答案:

答案 0 :(得分:0)

我会这样做:

  1. 为每个订单对象添加一个可观察的selectedTeacher
  2. value: selectedTeacher添加到您的选择中:

    <select class="form-control" data-bind="attr: { id: 'prefix_' + $index() }, options: TeacherNames, optionsValue: 'TeacherId', ..., value: selectedTeacher"></select>

  3. 检查RequestImage事件

    中的可观察对象
    if ( !data.selectedTeacher() ) {
            alert('Error: select teacher')
    } else {
            alert('Success')
    }
    
  4. 工作演示 - Fiddle