There are 2 input fields in my code that only accept positive floats with 2 decimals. Any other characters entered should be automatically removed using the change()
function.
Whenever the value of one input is changed, the value of the other input should also change automatically.
Error #1 - Main issue
The regular expression used does not restrict the number of decimal places to 2 and allows multiple periods (eg: 12.345.67 is accepted).
Error #2
The forbidden characters are not properly removed when calling the change()
function, resulting in the following error message:
Error: $scope.uc.replace is not a function
This error occurs because replace()
can only be applied to strings while math operators (+
, -
, *
, /
) work only with numbers. How can I resolve this conflict?
You can view and test my code on this JSFiddle link.
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.coeff = 0.5;
$scope.uf = '25';
$scope.uc = '';
$scope.change = function(type) {
console.log(type, "changes!");
$scope.uf = $scope.uf.replace(',', '.');
$scope.uf = $scope.uf.replace(/[^\d.-]/g, '');
$scope.uc = $scope.uc.replace(',', '.');
$scope.uc = $scope.uc.replace(/[^\d.-]/g, '');
if(type == 'uf') {
$scope.uc = $scope.uf * $scope.coeff;
} else if(type == 'uc') {
$scope.uf = $scope.uc / $scope.coeff;
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<input type="text" ng-model="uf" ng-change="change('uf')"/>
<input type="text" ng-model="uc" ng-change="change('uc')"/>
</div>