Search code examples
javascripthtmlknockout.jsknockout-3.0

Knockout js Table Edit column get onkeyup/ Onchange Latest Value. [Fiddle] (https://jsfiddle.net/chiks/975ncawv/521/)


I have a Knockout Model for Table. In Table 1 column is always editable. I wish to get the changed value of this column, i.e when the onchange/onKeyup event occurs the newly changed value should be availanle with me i.e in alert I should receive the newest changed value.

Below is just an sample code snippet. Please find Fiddle

<td>
      <input data-bind="event: {change:$parent.value_changed},value: Menge "/>  
  </td>  


 self.value_changed = ko.observable(self.items());
    refVM.value_changed.subscribe(function (newValue) {
   alert(newValue);
});

Solution

  • That's way more complicated than it needs to be.

    1. Observables by default fire change events whenever their value updates. You do not need to create an event binding in HTML to listen to changes. Keep it like this:

      <input data-bind="value: Menge "/>
      
    2. To listen the change events fired by this Menge observable, simply subscribe to it right after it is created (inside the RowModel constructor).

      var RowModel = function(bild,artikelnummer, bezeichnung,kategorie,preis,menge,preisgesamt,removePeople, werbemittelId) {
        this.Bild = ko.observable(bild);
        this.Artikelnummer = ko.observable(artikelnummer);
        ...
        this.Menge = ko.observable(menge);
        ...
      
        this.Menge.subscribe(function(newValue){
          alert(newValue);
        });
      };
      

    Here's the updated fiddle.