deepaksingh pawar
deepaksingh pawar

Reputation: 110

angularjs not focussing on next element

my html code:

<div ng-app="app">
<form>
    <div class="form-group">
      <label >Username</label>
      <input focus type="text" class="form-control" id="loginUserName" ng-model="userForm.crn" required/>  
      </div>
     <div class="form-group">
      <label >Password</label>         
       <input focus type="password" class="form-control" id="loginPwd" ng-model="userForm.password"  required/>
     </div>
</form>

my js Code:

var app = angular.module('app', []); app.directive('focus', function () {
return {
    restrict: 'A',
    link: function ($scope, elem, attrs) {

        elem.bind('keydown', function(e) {
        var code = e.keyCode || e.which;
        if (code === 13) {
          console.log(elem);
          elem.next()[0].focus();
          //e.preventDefault();
          //elem.next().focus();
        }
      });
    }
}
})

1: this code does not focus on next element when enter button is clicked. it shows nextElementSibling: null and nextSibling: text on console.log(elem) 2: but when i remove tag label and div in form tag, it starts working as it focuses on next element.

so, Question is how do i make it work without removing div and label. why is the nextElementSibling coming null?

this is fiddle link of this code

Upvotes: 1

Views: 4654

Answers (1)

Shailendra Sharma
Shailendra Sharma

Reputation: 6992

your dom traversing approch is wrong how can elem.next('') give you next input you need to get parent first than look for input inside next div

next() : method returns the next sibling element of the selected element. Sibling elements are elements that share the same parent.

try

elem.bind('keydown', function (e) {
                 elem.parent('div').next().find('input').focus();
            });

Working Fiddle

Explanation :

   elem.bind('keydown', function(e) {
               var code = e.keyCode || e.which;
               if (code === 13) {

                   console.log(elem); // "elem" is the current element which have focus you can see it in console it's always point to the current element .
                   elem.parent('div').next().find('input')[0].focus(); //Explained as following 

                 `elem.parent('div')`
                   to find parent div now we are on div which have
                   current element now `.next()`
                   to move to next div(next sibling element) and than find input inside it by `find('input')`
                   to make focus over it </b>

                   console.log(elem.parent('div')); //parent Div obj

               }

check here angularjs-dom-selector

Upvotes: 2

Related Questions