bailey.bailey
bailey.bailey

Reputation: 177

Adding 2 input values without NaN if input value is empty. AngularJS

I have a part in my form that takes in 2 input numbers and adds them together and displays the result.

<input type="number" ng-model="numb1" ng-blur"addInputs()">
<input type="number" ng-model="numb2" ng-blur"addInputs()">
<p><span ng-bind="sumOfNumbs"></span>

this is the Angular

numb1 = 0
numb2 = 0
addInputs = function() {
    sumOfNumbs = numb1 + numb2;
}

But if you delete all the contents of either of the < inputs> it displays NaN because numb1 or numb2 is equal to Null. How do i stop this?

Upvotes: 1

Views: 170

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222682

This happens when you don't initialize values, when it tries to add it will be Not a Number. Inorder to handle that you can use parseInt

parseInt($scope.numb1) + parseInt($scope.numb2); 

in your case you've initiatlized to 0, so you won't be getting a NAN as follows,

DEMO

var app = angular.module('testApp',[]);
app.controller('testCtrl',function($scope){
  $scope.numb1 = 0;
  $scope.numb2 = 0
$scope.addInputs = function() {
    $scope.sumOfNumbs = $scope.numb1 + $scope.numb2;
}

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="testApp">
 <div class="container" ng-controller="testCtrl">

<input type="number" ng-model="numb1" ng-blur="addInputs()">
<input type="number" ng-model="numb2" ng-blur="addInputs()">
<p><span ng-bind="sumOfNumbs"></span>
</div>

Upvotes: 1

Related Questions