<!DOCTYPE html>
<html>
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react.js" data-semver="0.13.3" data-require="react@*"></script>
</head>
<body>
<div id="example"></div>
<script src="CurrencyField.js"></script>
<script src="script.js"></script>
</body>
</html>
var App = React.createClass({
getInitialState: function() {
return {money: '$1,000.3'};
},
handleChange: function(value) {
this.setState({money: value});
},
render: function() {
return (
<div>
<CurrencyField value={this.state.money} onChange={this.handleChange} />
<div>{this.state.money}</div>
</div>
);
}
});
React.render(
<App />,
document.getElementById('example')
);
var CurrencyField = React.createClass({
componentWillMount: function () {
var value = this.convertToCurrency(this.props.value);
// format
this.props.value = new String(parseFloat(value).toFixed(2));
// notify that value changed
this.props.onChange(this.props.value);
},
render: function () {
return <input type="text" value={this.props.value} onChange={this.handleChange} />;
},
handleChange: function (event) {
this.convertToCurrency(event.target.value);
// notify that value changed
this.props.onChange(value);
},
convertToCurrency: function (input) {
value = new String(input);
// remove all characters that aren't digit or dot
value = value.replace(/[^0-9.]/g,'');
// replace multiple dots with a single dot
value = value.replace(/\.+/g,'.');
// only allow 2 digits after a dot
value = value.replace(/(.*\.[0-9][0-9]?).*/g,'$1');
// replace multiple zeros with a single one
value = value.replace(/^0+(.*)$/,'0$1');
// remove leading zero
value = value.replace(/^0([^.].*)$/,'$1');
return value;
}
});