Search code examples
javascriptangularjsangular-materialangularjs-watch

AngularJS - Set focus to next textbox after first textbox


Hi I am currently working of datetime picker input in my two textboxes.

enter image description here

What I want to do is, after the user choose date in the first textbox, a datetime picker of second textbox will pop up. The user does not need to click the second box.

This is my code.

html

<md-input-container>
    <input time="true" date="true" mdc-datetime-picker type="text" id="date" placeholder="Start Date" ng-model="date">
</md-input-container>

<md-input-container>
    <input time="true" date="true" mdc-datetime-picker type="text" id="date" placeholder="End Date" ng-model="date">
</md-input-container>

javascript

(function () {
  'use strict';

  angular
    .controller('DemoCtrl_{{boundField.name}}', function ($scope, mdcDateTimeDialog) {
      $scope.date = new Date('{{boundField.value()}}');
      $scope.dateTime = new Date();
      $scope.minDate = moment().subtract(1, 'month');
      $scope.maxDate = moment().add(1, 'month');

      $scope.displayDialog = function () {
        mdcDateTimeDialog.show({
          maxDate: $scope.maxDate,
          time: false
        })
          .then(function (date) {
            $scope.selectedDateTime = date;
            console.log('New Date / Time selected:', date);
          });
      };

    })
  ;
})();

enter image description here

I am new to angularjs expecially the javascript part. Your help is much appreciated. :)


Solution

  • Just use tab indexes like below

    Update

    I have updated the id and ng-model variables. You were using the same names for both start and end date whihc is not correct.

    HTML code is as below

    <md-input-container>
        <input time="true" date="true" mdc-datetime-picker type="text" id="startdate" placeholder="Start Date" ng-model="startdate" tabindex="1">
    </md-input-container>
    
    <md-input-container>
        <input time="true" date="true" mdc-datetime-picker type="text" id="enddate" placeholder="End Date" ng-model="enddate" tabindex="2">
    </md-input-container>
    

    The watcher code is as below

    $scope.$watch('startdate', function (oldval,newval) {
            if(oldval!=newval)
            {
                var enddate = document.getElementById('enddate');
                enddate.focus();
            }
        });
    

    Just add this watcher code in your controller

    Once you select the date in first textbox, it will check if the value is same as previous. If not then it will set the focus on the enddate.