jeremy jeremy - 8 days ago 4
Javascript Question

how to update a start and end page input field automatically

I have a list of start and end page numbers using angularJS forms. What i want to do is...for example if a user has entered the end page to be 4 on the first row, then I want the start page of the second row to be automatically updated with 5 (+1 of the previous end page).

I'm using an object that looks like this:

$scope.pages = {
items:[
{
startNumber:1,
endNumber:''
},
{
startNumber:'',
endNumber:''
},
{
startNumber:'',
endNumber:''
},
{
startNumber:'',
endNumber:''
}
]
};


HTML:

<div class="form-group col-sm-3" ng-repeat="file in pages.items">
<label for="start">Pages </label>
<input type="number" name="startPage" class="form-control" id="start" ng-model="file.startNumber">
<label for="end"> - </label>
<input type="number" name="endPage" class="form-control" id="end" ng-model="file.endNumber">
</div>


Function:

$scope.autoStartPageNumber = function (endPage) {
if(endPage.length) {
startNumber = endNumber + 1;
}
};


I'm not sure if i'm using the function correctly or where to put the function to add the numbers. If anyone has done anything similar to this..any help would be great

Answer

You can use ng-change on second input field and update the field accordingy. You can do something like this.

$scope.autoStartPageNumber = function(index) {
     if (index + 1 < $scope.pages.items.length) {
         $scope.pages.items[index + 1].startNumber = 1 + $scope.pages.items[index].endNumber;
     }
 };

var myApp = angular.module('myApp',[]);

//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope) {
    $scope.name = 'Superhero';
    $scope.pages = {
            items:[
                {
                      startNumber:1,
                      endNumber:''
                },
                {
                      startNumber:'',
                      endNumber:''
                },
                {
                      startNumber:'',
                      endNumber:''
                },
                {
                      startNumber:'',
                      endNumber:''
                }
            ]
      };
 $scope.autoStartPageNumber = function (index) {
 if(index +1 < $scope.pages.items.length){
   $scope.pages.items[index+1].startNumber=$scope.pages.items[index].endNumber + 1;
 }


      };
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<div class="form-group col-sm-3" ng-repeat="file in pages.items">
    <label for="start">Pages </label>
    <input type="number" name="startPage" class="form-control" id="start" ng-model="file.startNumber">
    <label for="end"> - </label>
    <input type="number" name="endPage" class="form-control" id="end" ng-model="file.endNumber" ng-change="autoStartPageNumber($index)">
</div>
</div>