AngularJS fails to prioritize the following element

Here is 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>

And here is my JavaScript 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 is not focusing on the next element when the enter button is clicked. It shows nextElementSibling: null and nextSibling: text on console.log(elem) 2: However, when I remove the label and div tags in the form tag, it starts working as it focuses on the next element.

So, the question is how do I make it work without removing the div and label? Why is the nextElementSibling coming up as null?

Here is the fiddle link of this code

Answer №1

Your method of traversing the DOM is incorrect. How can elem.next('') give you the next input? You need to first get the parent, then look for the input inside the next div.

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

Try this:

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

See working example on JSFiddle

Explanation:

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

        console.log(elem); // "elem" is the current element with focus
        elem.parent('div').next().find('input')[0].focus();

        console.log(elem.parent('div')); // Parent div object

    }

Check out this link for more information: angularjs-dom-selector

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to iterate through the calculation provided in order to generate 15 unique records and showcase it on the website?

How can I create a loop that generates up to 15 records based on the result of the first record, and then display them in a table format on a webpage? Input Example: Amount: 1500 Input One: 10 Desired Output Example: Sr. No. Value 1 1650 2 1815 ...

Using an AngularJS ng-repeat alias expression with multiple filters

As stated in the Angular ngRepeat documentation, the alias expression can only be used at the end of the ngRepeat: It's important to note that `as [variable name]` is not an operator, but rather a part of the ngRepeat micro-syntax and must be place ...

Modify components in a directive template depending on the information in the scope

In my project, I am facing an issue with a directive nested within an ng-repeat. The ng-repeat item is passed to the directive and I am trying to generate a directive template or templateUrl with dynamic elements based on a key/value in the item. Specifica ...

Is there a way to schedule a function to run every 6 hours in node.js based on actual time instead of the device's time?

var currentTime = new Date().getHours(); if(currentTime == 6){ //function Do stuff } if(currentTime == 12){ //function Do stuff } if(currentTime == 18){ //function Do stuff } if(currentTime == 24){ //function ...

PHP will send back a response code of 500, but only if it is submitted

Hey there! I've been working on implementing a two-step authentication system on a website, and I'm encountering an issue with an AJAX post. Every time I try to make the AJAX post, it returns a 500 Error. Oddly enough, when I directly run the co ...

What is the best way to activate an @keyframe animation based on the scrolling action?

I am currently working on an @keyframe animation that rotates a circle along its x-axis, starting from 0 degrees to 90 degrees and then back to 0 degrees. My objective is to synchronize the rotation of the circle with the user's scrolling movement on ...

Experiencing an issue with Jest - Error: unable to access property 'forEach' of null

After watching some tutorials, I decided to create a sample project in Jest for writing tests. In a TypeScript file, I included a basic calculation function like this: Calc.cs export class Calc { public add(num1: number, num2: number): number { ...

Stop the form from submitting when the enter key is pressed using VueJS and Semantic UI

After spending the past two days searching for a solution to this persistent issue, none of the suggested remedies have proven effective so far. My form's HTML structure is as follows: <form id="quote_form" action="" method="get" class="ui large ...

Mapping the changes in the checkbox of a material tree node

Check out this demo on StackBlitz: Tree View I'm having issues with the tree not displaying as desired. I would like it to look like this: Manager Sublist Manager 1 Manager 2 Manager 3 Could you please review and provide some advic ...

The package.json file engines field specifying the version with a tilde and then a greater than sign (~>)

When a package.json file includes an engines field such as this: "engines" : { "node" : "~>12" }, What is the significance of ~> in this context? ...

Steer clear of receiving null values from asynchronous requests running in the background

When a user logs in, I have a request that retrieves a large dataset which takes around 15 seconds to return. My goal is to make this request upon login so that when the user navigates to the page where this data is loaded, they can either see it instantly ...

Exploring the Synergy Between Play 2.3.x, Webjars, and Requirejs: Unveiling

Queries: Is there a way to streamline the process of setting paths and shims in requirejs for webjars and their dependencies without manual intervention? (Especially for webjars that include a requirejs.config() call?) Does anyone have a straightforward e ...

Floating elements can be vertically aligned with spans

I am facing an issue with aligning three spans vertically inside a div. It seems simple to achieve, but vertical alignment is not working properly when I use float. My goal is to have the light blue bar vertically centered. Here is the code snippet: .co ...

Combining keyframe properties in a more efficient way using less code

While attempting to develop a LESS mixin for CSS3 keyframes, I encountered the typical way of chaining IDs and classes: #idOne, #idTwo, .classOne, .classTwo { ... } Nothing groundbreaking there. What I'm currently working on is crafting the foll ...

Implementing tooltips using JavaScript within Bootstrap 5

Is there a way to add both a tooltip and popover to the same element in Bootstrap v5 via Javascript? I have attempted to enable both of them using JS as it seems like the best approach. The tooltip that was added through html is functioning correctly: ...

Display the element only when the request sent with getJSON exceeds a certain threshold of time in milliseconds

Here's a snippet of my JavaScript code: surveyBusy.show(); $.getJSON(apiUrl + '/' + id) .done(function (data) { ... surveyBusy.hide(); }) .fail(function (jqXHR, textStatus, err) { ... surveyBusy. ...

Identify Safari browser and redirect visitors

Here is the script I am using to detect and redirect a page specifically when Safari is used: if(/safari/.test(navigator.userAgent.toLowerCase())) { window.location.href = "elsewhere.html" } Currently, it redirects in both Safari and Chrome. How can ...

The central navigation system of the Owl Carousel

I am currently using the owl carousel plugin and I am struggling to figure out how to center align the navigation vertically while also using the autoHeight option. http://codepen.io/anon/pen/jJAHL I have attempted the following code snippet, but it seem ...

Unveiling the power of Next.js: Learn how to efficiently fetch pages using the traditional pages router

I'm currently working on a Next.js application with next version 13.4.13. The app follows the traditional pages directory structure. Within this setup, there are 2 main pages organized as follows: /pages/light /pages/heavy The light page is quite ...

The error in React syntax doesn't appear to be visible in CodePen

Currently, I am diving into the React Tutorial for creating a tic-tac-toe game. If you'd like to take a look at my code on Codepen, feel free to click here. Upon reviewing my code, I noticed a bug at line 21 where there is a missing comma after ' ...