Adjust focus dynamically on pressing enter in an HTML form

I am currently working on adjusting the functionality of my HTML input form to change focus upon pressing the enter key. I need to trigger the saveValue() function from the input field when the enter key is pressed and then move the focus to the next input field. I have been exploring a directive from Stack Overflow that deals with moving focus in AngularJS, but I am unsure how to customize it to fit my specific requirements.

angular.module('ionicApp', ['ionic'])
  .controller('appCtrl', function($scope) {
    $scope.inputs = [{
      value: ''
    }];
    var checkedValues = [];

    $scope.addField = function(index) {
      console.log(index);
      var name = {
        'value': ''
      };
      if ($scope.inputs.length <= index + 1 && $scope.inputs.length < 10) {
        $scope.inputs.splice(index + 1, 0, name);
      }
    }
    $scope.saveValue = function(ticked, item, index) {
      console.log(index);

      if (ticked) {
        if (index >= 0) {
          $scope.showButton = true;
        }
        checkedValues[index] = item;
        console.log(checkedValues);
      } else {
        var indexs = checkedValues.indexOf(item);
        if (indexs > -1) {
          checkedValues.splice(indexs, 1);
        }

        console.log(checkedValues);
      }

    }
  })
.small-input .item-checkbox .checkbox {
  position: absolute;
  top: 50%;
  right: 8px;
  left: 5px!important;
  z-index: 3;
  margin-top: -20px!important;
  transform: scale(1);
}
.checkbox-royal input:before,
.checkbox-royal .checkbox-icon:before {
  border-color: #000;
  background-color: #387ef5;
}
.checkbox-royal input:checked:before,
.checkbox-royal input:checked + .checkbox-icon:before {
  background: #099AD1;
  border-color: #387ef5;
}
<html>

<head>
  <link href="http://code.ionicframework.com/1.3.2/css/ionic.min.css" rel="stylesheet">
  <script src="http://code.ionicframework.com/1.3.2/js/ionic.bundle.js"></script>

</head>

<body ng-app="ionicApp" ng-controller="appCtrl">
  <form id="valueForm" ng-submit="submitValues()">
    <div class="small-input list padding" style="padding-top:4px;">
      <div ng-repeat="item in inputs  track by $index">
        <label class="item item-input">
          <input type="text" placeholder="" ng-model="item.value" ng-disabled="item.ticked">
          <ion-checkbox ng-click="addField($index)" ng-change="saveValue(item.ticked,item.value,$index)" ng-model="item.ticked" ng-disabled="!item.value" style="border: none;padding-left: 30px;" class="checkbox-royal"></ion-checkbox>
        </label>
      </div>
      <button type="submit" ng-show="showButton" class="button button-dark button-shadow pull-right" style=""><i class="ion-ios-arrow-forward"></i>
      </button>
    </div>

  </form>
</body>
</head>

Answer №1

If you encounter an issue with the directive keydown handler not recognizing the new input on the page, it may be because the input is created after the handler runs. One possible solution is to use a $interval to continuously check for the presence of the new input and then assign focus to it:

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

    // Set up an interval to monitor the addition of the new input
    scope.interval = $interval(function() {
      var e = $('input[type=text]');
      if (e.length === scope.inputs.length) {

        scope.cancel();
        // Focus on the last enabled input element
        $('input[type=text]:not(:disabled):last').focus();
      }
    }, 10);
  }
});

For a detailed demonstration and implementation of this process, I have provided a plunker link. In the main controller, I have included a new method called addFieldAndSave to handle the addition and saving functionalities.

https://plnkr.co/edit/2NXQB7N7bVxUVQk7PLsx?p=preview

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

Is Protractor compatible with Internet Explorer 9?

For my Angular App that is running on IE9, I need to create end-to-end acceptance tests. I'm curious to know if the browser simulated by Protractor matches the behavior of IE9 or a newer version? ...

Initializing an HTML5 video player directly from an Array

I am trying to populate a video player on my webpage with an array of videos. Here is the code I have so far: var current = 0; var videos = ["01", "02", "03", "04"]; function shuffle(array) { var currentIndex = array.length, temporaryValue, randomInde ...

Guide on organizing items into rows with 3 columns through iteration

Click on the provided JSFiddle link to view a dropdown menu that filters items into categories. Each item is stored as an object in an array for its respective category. Currently, all items are displayed in one column and I want to divide them into three ...

applying v-bind directive when the variable is null

I am using Vue and have a variable. If the variable has a value, I want to display an image (pic1). However, if the variable is empty, then I want to show another image (pic2). Here's my code... <template v-for="(item, index) in items"> <im ...

Identifying a specific item within an array

Can someone guide me on how to manipulate a specific object within an array of objects? For example: var myArray = [ {id: 1}, {id: 2}, {id: 3}, {id: 4} ] // Initial state with the 'number' set as an array state = { number: [] } // A functio ...

Utilizing interpolation for a CSS class defined in an external file within Angular 2

Is it feasible to send a variable to a CSS class in an external CSS file within Angular 2, such as: import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', sty ...

Switching from a vertical to horizontal tab layout in Angular 4 Material 2 using MD-Gridlist

I'm currently trying to modify the tabbing functionality within an MD-Gridlist so that it tabs horizontally instead of vertically. I've experimented with tab indexes but haven't had any success. My goal is to enable horizontal tabbing throug ...

Font Awesome icons occasionally display as squares, but typically they render correctly

I've noticed a strange issue on my website where the font awesome icons sometimes display as squares instead of their intended design. After searching through forums, it seems that my situation is different from others experiencing similar problems. I ...

Attempting to create a login and registration form

Hello, I am attempting to create a form that can generate new user accounts and passwords. These values should be stored from the input tag when the user clicks on the register button. Unfortunately, I am encountering an issue where clicking the register ...

Node and Express Fundamentals: Delivering Static Resources

const express = require('express'); const app = express(); app.use(express.static('public')); I've been attempting to complete the "Basic Node and Express: Serve Static Assets" challenge on freecodecamp, but it keeps showing as " ...

Binding variables in JSX with Vue.js scope involves connecting data directly to the template

I am in search of code similar to this: <div v-for="item in items" :key="item"> {{ item }} ... <div v-with:newValue="calculateValue(item)"> {{ newValue }} </div> </div> I'm not sure what to call this pattern, but ...

Utilizing functions as arguments in AngularJS 1.5 directives

app.controller('myController', [ '$scope', function ( $scope ) { $scope.doSum = function(x, y){ console.log(x+y); }; } ]); <cmp data-fn="doSum(x, y)"></cmp> app.directive('cmp&apo ...

Divs are being obstructed by the navigation bar

I am seeking a solution to prevent div elements from being positioned below my navigation/information bar when the screen width is minimized. The information bar has a height of 1200px and I would like it to stay on the left side without any overlapping fr ...

Modify the layout of a JSON data structure

Here is an example of an array: let array = [ {1: { "date": "2014-04-23 00:00:00", "volumetrie": "22458" }}, {2: { "date": "2014-05-02 00:00:00", "volumetrie": "30585" }}, {3: { "date" ...

increasing the SQL integer value with padding

Is it possible to apply padding to certain INT return values retrieved from an SQL database using CSS within a div tag? I need specific numbers to have padding-left: 20px; while other specific numbers should have padding-right: 20px;. This presents a styl ...

Internet Explorer is automatically inserting extra vertical space after the first list item in a basic menu design

Does anyone else have trouble with IE? (Or is it just me?) I'm creating a list with a background. The first and last LI elements are 5px high, while the others are 16px high. However, in IE there's a strange blank space between the first and se ...

The issue with grunt-contrib-compass not functioning properly within npm

I recently installed npm and grunt, followed by installing grunt-contrib-compass. However, when I try to run grunt, I encounter the following error: Running “compass:dist” (compass) task Warning: not found: compass Use –force to continue. Aborted du ...

How can the seating arrangement be optimized for a seating chart and what is the most effective way to transition away from a traditional table structure?

Currently, I am attempting to create a dynamic seating chart on a webpage within an asp.net-mvc site using data retrieved from a database. Initially, I used a table to organize the grid layout of rows and columns, which resembled this structure: The datab ...

Exploring the Angular HTTP interceptor functionality

Struggling to test my application's ability to log a user in with saved credentials and retry a request on a 401 error. The challenge lies in needing the initial call to return a 401 but then switch to a 200 response after the login request is made ag ...

Extracting information from a database (HTML, JavaScript)

I am currently working on a table that receives data from the server using ajax: $.each(data, function(i, item) { $('#MyTable tbody').append("<tr>" +"<td>" +data[i].A+ "</td><td>" +d ...