KnockOutJS将两个文本框值一起添加

时间:2013-07-12 14:44:20

标签: jquery knockout.js knockout-2.0

我所要做的就是让KnockOut将两个文本框的值加在一起,然后将结果放到第三个文本框中。

我在这里有一个JSFiddle:jsFiddle

我的HTML框是:

<input data-bind="value:AirportPickup" data-val="true" data-val-number="The field Airport Pickup £10 per person must be a number." data-val-required="The Airport Pickup £10 per person field is required." id="AirportPickup" name="AirportPickup" type="text" value="0" />

<input data-bind="value:PackedLunch" data-val="true" data-val-number="The field Packed Lunch £6.50 must be a number." data-val-required="The Packed Lunch £6.50 field is required." id="PackedLunch" name="PackedLunch" type="text" value="0" />

<input data-bind="value:Breakfast" data-val="true" data-val-number="The field Breakfast £6.00 must be a number." data-val-required="The Breakfast £6.00 field is required." id="Breakfast" name="Breakfast" type="text" value="0" />

...我的jQuery是:

$(document).ready(function () {

function AppViewModel() {
    this.AirportPickup = ko.observable("");
    this.PackedLunch = ko.observable("");
    this.Breakfast = AirportPickup + PackedLunch;
}
ko.applyBindings(new AppViewModel());
});

当我在前两个文本框中添加任何内容时,没有任何事情发生。

有人可以帮忙吗?

谢谢

3 个答案:

答案 0 :(得分:3)

使用computed observable

http://jsfiddle.net/7kQP6/

$(document).ready(function () {

    function AppViewModel() {
        this.AirportPickup = ko.observable(0);
        this.PackedLunch = ko.observable(0);
        this.Breakfast = ko.computed(function () {
            return Number(this.AirportPickup()) + Number(this.PackedLunch())
        }, this);
    }
    ko.applyBindings(new AppViewModel());
});

请注意,此代码需要一些验证(例如,确保输入是一个数字)。

答案 1 :(得分:2)

另一种方式可能是

http://jsfiddle.net/7kQP6/1/

只需在data-bind

中设置值即可
 <input data-bind="value:AirportPickup" data-val="true" data-val-number="The field Airport Pickup £10 per person must be a number." data-val-required="The Airport Pickup £10 per person field is required." id="AirportPickup" name="AirportPickup" type="text" value="0" />

<input data-bind="value:PackedLunch" data-val="true" data-val-number="The field Packed Lunch £6.50 must be a number." data-val-required="The Packed Lunch £6.50 field is required." id="PackedLunch" name="PackedLunch" type="text" value="0" />

<input data-bind="value:Number(AirportPickup()) + Number( PackedLunch())" data-val="true" data-val-number="The field Breakfast £6.00 must be a number." data-val-required="The Breakfast £6.00 field is required." id="Breakfast" name="Breakfast" type="text" value="0" />;

答案 2 :(得分:1)

this.Breakfast需要是一个计算的可观察量:

this.Breakfast = ko.computed(function() {
 return this.AirportPickup + this.PackedLunch;
});