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 locating specific elements on Yahoo News with Selenium in Python?

I am currently facing some challenges with extracting comments from Yahoo News using Selenium. I have successfully clicked on the comments button to open it, but now I am struggling to locate the text of the comments section. from selenium import webdriver ...

What is the recommended lifecycle hook in Vue.js2 to execute a function when the page is loaded?

I have a dynamic table that can be filled with various numbers of rows, and I want to add an overlay before the data is loaded using my applyOverlay() function. Below is the structure of my HTML: <table id="table" class="datatable" s ...

Add the file retrieved from Firestore to an array using JavaScript

Trying to push an array retrieved from firestore, but encountering issues where the array appears undefined. Here is the code snippet in question: const temp = []; const reference = firestore.collection("users").doc(user?.uid); firestore .collec ...

Unrecognized files located within the same directory

My main.html file located in the templates folder also contains three additional files: date.js, daterangepicker.js, and daterangepicker.css. Despite including them in the head of the HTML as shown below: <script type="text/javascript" src="date.js"> ...

Using RabbitMQ in a Node.js application to illustrate an example of header exchange

I've been on a quest to find an example of using RabbitMQ with Node.js for a headers exchange. If anyone could guide me in the right direction, I would greatly appreciate it. Here's what I've managed to put together so far: The publisher me ...

How to effectively use the LIKE statement in mysql with node.js

app.post('/like/:level/:name', function(req, res){ connection.query("SELECT * from books where " + req.params.level + " like '%" + req.params.name + "'%", function(err, rows, fields) { if (!err){ var row = rows; res.send(row); console.l ...

Determine the number of network requests being made on a webpage

In my quest to develop a universal method using selenium, I am seeking a way to ensure that all background network activities, including Ajax, Angular, and API calls, have completed. While I am aware of the option to determine the number of active Ajax cal ...

Ways to modify the color of mat-icon within an input field using Angular 6

Here is the code from my HTML file: <div class="input-field"> <div> <input type="text" id="name" required email/> <label for="name">Email: <mat-icon svgIcon="mail" class="change-color"></mat-icon> &l ...

Determine if an HTML element contains a specific class using JavaScript

Is there a simple method to determine if an HTML element possesses a particular class? For instance: var item = document.getElementById('something'); if (item.classList.contains('car')) Remember, an element can have more than one clas ...

Swapping images when hovering over a list item or anchor tag

I recently came across an intriguing issue with changing the img src on a:hover. Check out this SCREENSHOT When hovering over the <a> sector, it's not showing the white image as expected. I have black and white icons, and I want the img src to ...

Removing element from database using php/ajax

My PHP script dynamically generates rows of <div> elements with 5 items per row. My next goal was to create a select form with dynamically generated options for deleting the selected item. However, I encountered an issue where the dynamically genera ...

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 ...

Creating a stylish horizontal divider with circular accents at either end

Can someone help me create a border similar to the one shown in this image? I've attempted using the :after and :before CSS attributes, but without success. The HTML element is an h1 that requires a border at the bottom. Is it achievable? ...

The jQuery Deferred feature on Ajax is failing to properly pass the array in the data option as an array, instead converting

I am facing an issue in my application where I want to use jQuery deferred to handle Ajax success and error uniformly from a central location. It works perfectly fine when I pass strings in the data option, but when I try to pass an array, it gets sent as ...

The jQuery resize() method seems to be malfunctioning

My jQuery resize function is not working properly. I am trying to implement a custom scroll for devices with a width of 767, but it doesn't seem to be functioning as expected. Normally, the scroll works on devices above 767 in width. How can I fix thi ...

Effortlessly move and rearrange various rows within an HTML table by utilizing JQuery alongside the <thead> elements

My JsFiddle has two tables and I want to switch rows <tr> between them using Jquery. However, due to the presence of the <thead> tag, it is not functioning properly. I suspect that the issue lies with the items in the selector, but I am unsure ...

Uncertainty surrounding the extent of a button's scope within an Angular application

(click) event in one instance of a component is causing the function in another instance to be triggered unexpectedly. I am having trouble describing this issue. For reference, I have included a working example on stackblitz. When clicking on both buttons ...

I'm struggling to locate the space that should be between these elements

After accidentally starting in quirks mode without declaring a doctype, I realized my mistake and corrected it by declaring a doctype. However, there is a persistent issue with a space between .car-box-img and car-box that I can't seem to locate in t ...

What is the best way to synchronize the image dimensions and source when dynamically loading images?

I am facing an issue with a function that updates images by altering the src and css (width/height) of an IMG tag within the document. Below is a simplified example to demonstrate the problem: updateImage = function(src, width, height) { $("#changeMe"). ...

The concept of Ajax and checkbox arrays

I recently started working with Ajax and tried following a tutorial from this source However, I encountered some issues while trying to make it work. Can someone please assist me with this? Below is the HTML code that I am using: <html> <head ...