【问题标题】:Trying to figure out how to update hidden input with value from select in Knockout试图弄清楚如何使用 Knockout 中的选择值更新隐藏的输入
【发布时间】:2017-02-11 03:41:28
【问题描述】:

我很难理解这个问题。我正在使用 KnockoutJS,并且我有一个可观察的选择下拉菜单。当我更改该下拉列表的值时,我希望它在我的表中每行更改一个隐藏输入。我无法弄清楚如何在订阅函数中设置该值。我知道订阅函数被调用是因为我的控制台输出运行。

这是我的 HTML 选择和我想要更改的隐藏输入的部分表格:

<div data-bind="if: (availableProfitCodes().length > 1)">
                <select id="profitCode" data-bind="value: selectedProfitCode, options: availableProfitCodes, optionsText: function(code) { return code.name + ' : ' + code.desc }, optionsValue: 'code', optionsCaption: '-- select a profit code --'"></select>
            </div>
<tbody data-bind="foreach: codes">
                <tr>
                    <td>
                        <input data-bind="value: itemNo, attr: { name: 'brochureProfitCodes[' + $index() + '].itemNo', id: 'brochureProfitCodes_' + $index() + '__itemNo' }, validationOptions: { errorElementClass: 'input-validation-error' }" class="form-control" readonly="readonly" tabindex="-1" />
                        <input data-bind="value: profitCode, attr: {name: 'brochureProfitCodes[' + $index() + '].profitCode', id: 'brochureProfitCodes_' + $index() + '__profitCode' }" type="hidden" class="profitCode" />
                    </td>

还有我的淘汰码(不工作的部分在订阅函数中):

var CodeModel = function(data) {
        var self = this;

        self.profitCode = ko.observable(data ? data.profitCode : '');

        self.itemNo = data.itemNo;
        self.brocCode = data.brocCode;
        self.brochureID = data.brochureID;
        self.itemDesc = data.itemDesc;
        self.retail = data.retail;
        self.wholesale = data.wholesale;
        self.commission = data.commission;
    }

    var codesModel = function(codes) {
        var self = this;
        self.availableProfitCodes = ko.observableArray([]);
        self.selectedProfitCode = ko.observable();

        //self.codes = ko.observableArray(codes);
        //self.codes = ko.observable(new CodeModel());
        if(codes != null) {
            self.codes = ko.observableArray(codes.map(function(code) { return new CodeModel(code) }));
        }            

        self.selectedProfitCode.subscribe(function(newValue) {
            console.log("newValue is: " + newValue);
            self.codes.profitCode(newValue);
        });
    };
$(document).ready(function () {

        var profitCodeInt = Number($.trim($("#pCode").val()));
        if(profitCodeInt == 0) { // adding a new profit code
            ...
        }
        else if(profitCodeInt > 0) { // editing an existing profit code
            $.ajax({
                url: '@Url.Action("GetProfitCodesJSON", "Brochure")',
                type: 'POST',
                success: function(json) {
                    var codesJSON = @Html.Raw(Json.Encode(Model.brochureProfitCodes));
                    console.log(JSON.stringify(codesJSON));
                    var itemsJSON = @Html.Raw(Json.Encode(Model.brochureItems));
                    viewModel = new codesModel(codesJSON);
                    var result = json.profitCodes.filter(function( obj ) {
                        return obj.profitCode == profitCodeInt;
                    });
                    var code = new profitCode(result[0].profitCode, result[0].profitDesc, result[0].profitName);
                    viewModel.availableProfitCodes.push(code);
                    ko.applyBindings(viewModel, $("#profitModal")[0]);
                }
            });

【问题讨论】:

  • 你有几个版本的codeModel.codes,所以我不确定你目前使用的是什么,但我认为codes应该是一个数组?如果是这样,您只需要遍历每个项目并设置项目的利润代码,而不是在集合本身上设置利润代码。 for(var x=0; x

标签: javascript knockout.js


【解决方案1】:

self.codes 是一个observableArray,所以你需要使用self.codes() 并循环遍历

var CodeModel = function(data) {
  var self = this;

  self.profitCode = ko.observable(data ? data.profitCode : '');

  self.itemNo = data.itemNo;
  self.brocCode = data.brocCode;
  self.brochureID = data.brochureID;
  self.itemDesc = data.itemDesc;
  self.retail = data.retail;
  self.wholesale = data.wholesale;
  self.commission = data.commission;
}

var codesModel = function(codes) {
  var self = this;
  self.availableProfitCodes = ko.observableArray(options);
  self.selectedProfitCode = ko.observable();

  //self.codes = ko.observableArray(codes);
  //self.codes = ko.observable(new CodeModel());
  if (codes != null) {
    self.codes = ko.observableArray(codes.map(function(code) {
      return new CodeModel(code)
    }));
  }

  self.selectedProfitCode.subscribe(function(newValue) {
    self.codes().forEach(function(code) { code.profitCode(newValue); });
  });
};

var initCodes = [{ profitCode: 'ABC', itemNo: 1}, { profitCode: 'DEF', itemNo: 2 }];
var options = [
  { name: 1, desc: 'one', code: 'IJK' }, 
  { name: 2, desc: 'two', code: 'LMN' },
  { name: 3, desc: 'three', code: 'OPQ' }
];

ko.applyBindings(new codesModel(initCodes));
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div data-bind="if: (availableProfitCodes().length > 1)">
  <select id="profitCode" data-bind="value: selectedProfitCode, options: availableProfitCodes, optionsText: function(code) { return code.name + ' : ' + code.desc }, optionsValue: 'code', optionsCaption: '-- select a profit code --'"></select>
</div>
<table>
  <tbody data-bind="foreach: codes">
    <tr>
      <td>
        <input data-bind="value: itemNo, attr: { name: 'brochureProfitCodes[' + $index() + '].itemNo', id: 'brochureProfitCodes_' + $index() + '__itemNo' }, validationOptions: { errorElementClass: 'input-validation-error' }" class="form-control" readonly="readonly"
        tabindex="-1" />
        <input data-bind="value: profitCode, attr: {name: 'brochureProfitCodes[' + $index() + '].profitCode', id: 'brochureProfitCodes_' + $index() + '__profitCode' }" type="hidden" class="profitCode" /><span data-bind="text: profitCode"></span>
      </td>
    </tr>
  </tbody>
</table>

【讨论】:

  • 完美运行!非常感谢!
猜你喜欢
  • 2020-08-27
  • 2020-07-05
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
相关资源
最近更新 更多