Skip to content

Instantly share code, notes, and snippets.

@rahulpnath
Created July 9, 2014 06:46
Show Gist options
  • Save rahulpnath/b318efb34becd0865ace to your computer and use it in GitHub Desktop.
Save rahulpnath/b318efb34becd0865ace to your computer and use it in GitHub Desktop.
A Pen by Rahul P Nath.
Enter a value and tab off and you will see the currency $ coming in automatically.
<p>Enter bid price: <input data-bind="value: formattedPrice"/></p>
function MyViewModel() {
this.price = ko.observable(25.99);
this.formattedPrice = ko.computed({
// Similar to Convert function on IValueConverter
read: function () {
return '$' + this.price().toFixed(2);
},
// Similar to ConvertBack on IValueConverter
write: function (value) {
// Strip out unwanted characters, parse as float, then write the raw data back to the underlying "price" observable
value = parseFloat(value.replace(/[^\.\d]/g, ""));
this.price(isNaN(value) ? 0 : value); // Write to underlying storage
},
owner: this
});
}
ko.applyBindings(new MyViewModel());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment