通过比较两个输入字段中的值来启用/禁用元素

时间:2017-12-22 20:52:19

标签: javascript html knockout.js

我有两个输入字段值,我想知道如果第一个输入值大于第二个输入值,我怎么能禁用一个按钮。它仅使用第一个字母,但超过2个数字不起作用。

<button type="submit" data-bind="click: addition, enable:temp1() > temp2()" >Click here for addition</button>

 function ViewModel () {
            var self = this;
            self.var1 = ko.observable(0);
            self.var2 = ko.observable(0);
            self.temp1 = ko.observable(self.var1())
            self.temp2 = ko.observable(self.var2())

            this.addition = function() {
               self.var1(Number(self.temp1()));
               self.var2(Number(self.temp2()));

               this.var3 = self.var1() + self.var2();
               alert("Addition is = "+ this.var3 );
            };
         };

         var vm = new ViewModel();
         ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<p>First #: <span data-bind = "text: var1" > </span></p>
<p>Sectond #: <span data-bind = "text: var2" > </span></p>

         <p>Enter first #: <input data-bind = "value: temp1" /></p>
         <p>Enter second #: <input data-bind = "value: temp2" /></p>
         
         
         <p><button type = "submit" data-bind = "click: addition" enable="temp1() < temp2()" >Click here for addition</button></p>

1 个答案:

答案 0 :(得分:1)

提交按钮上的数据绑定属性出现错误。改变这个:

data-bind = "click: addition" enable="temp1() < temp2()"

到此:

data-bind = "click: addition, enable:Number(temp1()) < Number(temp2())"

此外,将Observable包装在Number构造函数中会强制该值为数字。以下是the enable binding

的文档