siuri
siuri

Reputation: 191

Enabled/Disable elements by comparing values in two input fields

I have two input field values and am wondering how can I disable a button if first input value is greater than second input value. It works with only first letter but more than 2 numbers are not working.

<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>

Upvotes: 1

Views: 294

Answers (1)

Jonathan Chaplin
Jonathan Chaplin

Reputation: 2482

there's a mistake in your data-bind attribute on the submit button. Change this:

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

to this:

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

Additionally, wrapping the observable in the Number constructor forces the value to be a number. Here is the documentation for the enable binding

Upvotes: 1

Related Questions