i read many tutorials but i dont know how to do this, this is the input
input(type="text",name="price",id="price"data-bind="text: price,valueUpdate:['afterkeydown','propertychange','input']")
and this is my viewModel
price: ko.computed(function()
{
return parseFloat(this.replace(' ','').replace(/[^0-9\.]+/g,"")) || '';
},this)
but this cause error: this has no method replace??? how can i pass the price value to the computed function??
We can restrict user to input user more than two decimal number Ex. 23.81, 3452.83 Modified code is as below. The reference code is taken from the @Martin Surynek answer.
HTML -
Script -
Knockout has extenders for this. Check This from knockoutjs.com explaining how to use observable extenders to force input to be numeric. I paste the code from the documentation here:
Source code: View
Source code: View model
Create you data-bind pointing at your shiny new code:
Shiny new knockout code:
This means that every time you update the price, it will apply the logic in the function (in this case stripping out anything that isn't a number or a period), and apply it directly to the price. You can also add other validation or cool features here, like adding a currency sybmol at the start, keeping it to 2 decimal places, etc...
Is better to create custom binding http://knockoutjs.com/documentation/custom-bindings.html which accept only allowed characters [0-9,.] as numeric representation.
put this line into your view
put this line into your model (remember to bind number as observable property)