Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I would add a couple of computed observables in there to do the parsing:</p> <pre><code> var viewModel = { num1: ko.observable(0), num2: ko.observable(0) }; viewModel.num1Parsed = ko.computed(function () { return viewModel.num1().replaceAll(',', '.'); }, viewModel); viewModel.num2Parsed = ko.computed(function () { return viewModel.num2().replaceAll(',', '.'); }, viewModel); viewModel.total = ko.computed(function () { return parseFloat(viewModel.num1Parsed()) + parseFloat(viewModel.num2Parsed()); }, viewModel); </code></pre> <p>I use the following function for replaceAll:</p> <pre><code>/** * ReplaceAll by Fagner Brack (MIT Licensed) * Replaces all occurrences of a substring in a string */ String.prototype.replaceAll = function (token, newToken, ignoreCase) { var str, i = -1, _token; if ((str = this.toString()) &amp;&amp; typeof token === "string") { _token = ignoreCase === true ? token.toLowerCase() : undefined; while ((i = ( _token !== undefined ? str.toLowerCase().indexOf( _token, i &gt;= 0 ? i + newToken.length : 0 ) : str.indexOf( token, i &gt;= 0 ? i + newToken.length : 0 ) )) !== -1) { str = str.substring(0, i) .concat(newToken) .concat(str.substring(i + token.length)); } } return str; }; </code></pre> <p>Alternatively, you could just replace your num1 and num2 observables in the HTML with a computed that parses as the value is written to it:</p> <pre><code> this.num1Parsed = ko.dependentObservable({ read: function () { return viewModel.num1(); }, write: function (value) { viewModel.num1(value.replaceAll(',', '.')); }, owner: this }); this.num2Parsed = ko.dependentObservable({ read: function () { return viewModel.num2(); }, write: function (value) { viewModel.num2(value.replaceAll(',', '.')); }, owner: this }); </code></pre> <p>.. and then change your HTML to:</p> <pre><code>&lt;input type="text" data-bind="value: num1Parsed, valueUpdate: 'keyup'"/&gt; &lt;input type="text" data-bind="value: num2Parsed, valueUpdate: 'keyup'"/&gt; &lt;input type="text" data-bind="value: total"/&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload