Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind multiple input with the same obervable knockoutjs to perform the same action

Tags:

knockout.js

I want to bind multiple text input with the same observable (same action)

<input id="test1" name="test1" type="text" data-bind="value: searchQuantity"/>
<input id="test2" name="test2" type="text" data-bind="value: searchQuantity"/>

var viewModel = {
        searchQuantity: ko.observable(),
    };


<p>You have typed: <span id="spantest1" data-bind="text: searchQuantity"></span></p>
<p>You have typed: <span id="spantest2" data-bind="text: searchQuantity"></span></p>

but when I change the value of input test1 it changes the value of test2.

I want to do the same action on the two inputs, but I want to change the value of the correspondent span. (This is just a sample so I can do the same on a grid with textboxes; I want on change of a textbox recalculate the sum of all the textboxes on the same column which contains the changed textbox.)


I think I didn't explain well my problem.

Please take a look at the screenshot
enter image description here

What I really want is when changing values in the red text boxes, the green cells will be updated with the sum of the column (the sum will be by year).

Thanks.

like image 540
user1856386 Avatar asked Nov 12 '22 16:11

user1856386


1 Answers


Please take a look on this demo I've created for you.
HTML Code

<input id="test1" name="test1" type="text" data-bind="value: searchQuantity1, valueUpdate:'afterkeydown'"/>
<input id="test2" name="test2" type="text" data-bind="value: searchQuantity2, valueUpdate:'afterkeydown'"/>

<p>Test1 value is : <span id="spantest1" data-bind="text: searchQuantity1"></span></p>
<p>Test2 value is : <span id="spantest2" data-bind="text: searchQuantity2"></span></p>
<p>Sum: <span id="spantest3" data-bind="text: spans"></span></p>


Javascript Code

var viewModel = function(data) {
  var self = this;
  self.searchQuantity1 = ko.observable(1);
  self.searchQuantity2 = ko.observable(2);
  self.spans = ko.computed(function() {
      return Number(self.searchQuantity1 ())+Number(self.searchQuantity2 ());
  }, self);
};

ko.applyBindings(new viewModel());


Does it answer you question?
Thanks.

like image 135
Pavlo Avatar answered Jan 04 '23 02:01

Pavlo