JSFiddle - React, Tailwind, and code Playground
by abuhamzah
HTML
<div ng-app="myApp">
<h3>input type="text" does not add up</h3>
A:<input type="text" ng-model="a1" numbers-only="numbers-only" maxlength="4"/>
<br/>
B:<input type="text" ng-model="b1" numbers-only="numbers-only" maxlength="4" />
<br>
C:<input type="text" ng-model="c1" numbers-only="numbers-only" maxlength="4"/>
<br/>
D:<input type="text" ng-model="d1" numbers-only="numbers-only" maxlength="4" />
<br>
Amount tendered (E): <input type="text" ng-model="e1" numbers-only="numbers-only" />
<hr/>
<h3>{{ change = (a1 *1 + b1 *1 + c1 *1 + d1 *1)}} </h3>
<h1>{{e1 - change | currency}}</h1>
</div>
JavaScript
angular.module('myApp', []).directive('numbersOnly', function(){
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
// this next if is necessary for when using ng-required on your input.
// In such cases, when a letter is typed first, this parser will be called
// again, and the 2nd time, the value will be undefined
if (inputValue === undefined) return ''
var transformedInput = inputValue.replace(/[^0-9+.]/g, '');
if (transformedInput!==inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
});