Move the focus to the previous input field by removing the key

I have created a phone number input with 10 fields that automatically skip to the next field when you fill in each number.

However, I would like to be able to go back to the previous field if I make a mistake and need to delete a digit. How can I achieve this functionality?

You can view my CodePen project here: http://codepen.io/Steve-Jones/pen/qdMjWb/

Here is the HTML code:

<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<body>
  <div class="phone-field"> 
    (<input class="phone-input" name="phone-input" type="tel" size="1" maxlength="1" placeholder="5" autofocus="autofocus">
    <input class="phone-input" name="phone-input" type="tel" size="1" maxlength="1" placeholder="5">
    <input class="phone-input" name="phone-input" type="tel" size="1" maxlength="1" placeholder="5">)
    <input class="phone-input" name="phone-input" type="tel" size="1" maxlength="1" placeholder="5">
    <input class="phone-input" name="phone-input" type="tel" size="1" maxlength="1" placeholder="5">
    <input class="phone-input" name="phone-input" type="tel" size="1" maxlength="1" placeholder="5"> -
    <input class="phone-input" name="phone-input" type="tel" size="1" maxlength="1" placeholder="5">
    <input class="phone-input" name="phone-input" type="tel" size="1" maxlength="1" placeholder="5">
    <input class="phone-input" name="phone-input" type="tel" size="1" maxlength="1" placeholder="5">
    <input class="phone-input" name="phone-input" type="tel" size="1" maxlength="1" placeholder="5">
</body>

This is the CSS code:

.phone-field {
  margin: 50px;
  font-size: 20px;
}

.phone-input {
  width: 13px;
  text-align: center;
  font-size: 16px !important;
  height: 1.75em;
  border: 0;
  outline: 0;
  background: transparent;
  border-bottom: 2px solid #ddd;
  margin-right: 2px;
  margin-left: 2px;
}

[placeholder]:focus::-webkit-input-placeholder {
  transition: opacity 0.5s 0.0s ease;
  opacity: 0;
}

And finally, here is the jQuery code:

$(document).ready(function(){
  $('body').on('keyup', 'input.phone-input', function(){
    if($(this).val().length === this.size){
      var inputs = $('input.phone-input');
      inputs.eq(inputs.index(this) + 1).focus();
    }
  });
});

Answer №1

Unlocking the potential with key codes: View on CodePen

$(document).ready(function(){

    $('body').on('keyup', 'input.phone-input', function()
    {
      var key = event.keyCode || event.charCode;
      var inputs = $('input.phone-input');
      if(($(this).val().length === this.size) && key != 32)
      {
        inputs.eq(inputs.index(this) + 1).focus();  
      } 
      if( key == 8 || key == 46 )
      {
        var indexNum = inputs.index(this);
        if(indexNum != 0)
        {
        inputs.eq(inputs.index(this) - 1).val('').focus();
        }
      }

    });
  });

Upon reviewing your code, I noticed that pressing the space bar moves the cursor to the next index. To address this, I believe this solution is appropriate.

KeyCodes Used:

Backspace = 8

Delete = 46

Space Bar = 32

Answer №3

To ensure the key event is delete and then focus before element, make sure to update your javascript file as shown below for successful implementation:

$(document).ready(function(){
    $('body').on('keyup', 'input.phone-input', function(e){
      if($(this).val().length === this.size){
        var inputs = $('input.phone-input');
        inputs.eq(inputs.index(this) + 1).focus();
      }
      if(e.keyCode == 8 || e.keyCode == 46){
        var inputs = $('input.phone-input');
        inputs.eq(inputs.index(this) - 1).focus();
      }
    });  
  });

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

Having trouble configuring webpack for CSS Modules? You may be dealing with an invalid configuration object

Encountering an issue while setting up webpack for CSS Modules... An error message is appearing stating that the configuration object is invalid. It seems that the output path specified as "build" is not an absolute path, which is required. Below are ext ...

What could be the source of this margin or spacing?

Within this test, I have noticed that there are 2 inline flex containers. Specifically, I am referring to the test scenario that states Next The flex containers are laid out inline. Despite the fact that there is some space between the containers, upon in ...

Is it possible for a Django view to send JSON data back upon a successful Ajax request?

I've tested both JsonResponse and HttpResponse (along with json.dumps), but even though ajax returns successfully, the returned JSON cannot be parsed by $.parseJSON(returned_json). I'm certain that the issue does not lie with parsing ($.parseJSO ...

Problem with jQuery image gallery

Currently, I am in the process of creating a simple image gallery that enlarges an image when it is clicked. To achieve this functionality, I am utilizing jQuery to add and remove classes dynamically. $(".image").click(function() { $(this).addClass("b ...

Load a webpage using javascript while verifying permissions with custom headers

Seeking guidance as a novice in the world of JavaScript and web programming. My current project involves creating a configuration web page for a product using node.js, with express serving as the backend and a combination of HTML, CSS, and JavaScript for t ...

If the div element undergoes a change, use an if-else condition to populate the data fields accordingly

I'm looking to create a basic if/else statement in JavaScript that checks if a div element has changed before populating JSON data fields/variables that pull from dynamically updated HTML. I want to avoid using the deprecated DOMSubtreeModified metho ...

Transforming a high chart into an image and transmitting it to the server through an ajax request

I am looking for a way to save multiple charts as PDF files on the server using an AJAX call. Each chart is rendered in a distinct container on the same page, and I need to convert them into images before sending them to the server for export. Any assist ...

Changes in a portion of the state for Vaadin's AbstractJavascriptComponent

I am currently working on implementing a JavaScript-based component for Vaadin that will be responsible for displaying and updating a large data set. To achieve this, I am extending AbstractJavaScriptComponent. My goal is to keep the JavaScript side as si ...

Implementing Event Listeners in Vue 3.0: A Guide to Attaching to the Parent Element

How can I attach an addEventListener to the parent element in Vue 3.x? I discovered that you can access the parent by using this code: import { getCurrentInstance, onMounted } from 'vue' onMounted(() => { console.log(getCurrentInstance() ...

Substitute numerical strings with actual numbers within an array

I need to transform an array from arr = ["step","0","instruction","1"] to newArr = ["step",0,"instruction",1] Below is the code I am using for this operation: newArr = arr.map((x) => { ...

Issue with the flexbox div not fully occupying the vertical space

I can't seem to get flexbox to fill the spaces as I want it to. I've been trying to figure out what I'm missing, but I just can't wrap my head around it. Here's a recreation of the issue with a link to a codepen. I want the div in ...

The compatibility between Polymer JS and Rails Turbolinks is problematic

Currently, I am facing a challenge in integrating PolymerJs with a Ruby on Rails project that has Turbolinks enabled. The issue arises when I click on a link - the new page loads correctly but my Polymer components do not reinitialize. They appear as if no ...

`The Art of Binding() with Objects Created on the Fly`

Currently facing challenges with rebinding something using a dynamically created object from prepend. Despite trying several methods, I am only able to unbind. Seeking assistance. $(document).ready(function(){ $(".newdir").click(function(){ $(".d-exp ...

Using Javascript to open a PDF in a new tab directly from a byte array

I am currently using AngularJS along with an HTTP resource to make a request to an external API. The response I am getting back is in the form of a byte array. My goal is to convert this byte array into a PDF and open it in a new window. So far, I have not ...

Designing a dropdown menu within displaytag

I am currently utilizing displaytag to present tabular data, but I aspire to design a user interface akin to "kayak.com" where clicking on a row reveals additional details without refreshing the page. Here is an example scenario before clicking the Detail ...

How can I make the Struts2 iterator function correctly?

Using the Struts2 <iterator> tag in a JSP to display values, the method is being called but no results are appearing on the page. All the necessary data is printing in the console, but not in the JSP itself. The call made is localhost\listAddCo ...

Issue with React Hot Toast not displaying properly due to being positioned behind the <dialog>

The Challenge of Toast Notifications Visibility with <dialog> Element tl;dr When utilizing the native dialog.showModal() function, the <dialog> element appears to consistently remain on top, which causes toast notifications to be obscured by ...

Struggling to retrieve JSON data from the MercadoLibre API while consistently encountering the CORS error?

I have been attempting to access a mercadolibre API that provides JSON data I need to utilize. However, whenever I make an AJAX GET request, I keep receiving the same error: "Response to preflight request doesn't pass access control check: It does n ...

Guidelines for displaying user profile information in the dashboard page through an Angular project, considering the different user types (user, super user, admin)

In my application, I have implemented the dashboard feature. There are three types of dashboards: the regular user dashboard, super user dashboard, and admin dashboard. The super user and admin dashboards include additional tables along with the data from ...

tips for linking my webpage with the database

While working on a registration page, I encountered an issue where the entered information was not being stored in the database. Instead, an error message appeared: Notice: Undefined variable: sql in C:\xampp\htdocs\Bawazir\Untitled-1. ...