What is the best way to prevent non-integer input in the last text box?

Currently, I am in the process of developing a JavaScript code.

I have included 4 text boxes in the layout that allow only one character to be inputted into each box.

An important guideline for this task is that the rightmost field holds the id "first" while the leftmost field is identified with the id "fourth."

There are specific conditions that must be met:

  1. The order of input should begin from the last text box (rightmost/first), moving sequentially to the second, third, and finally the fourth text box.

  2. The value entered in the rightmost/first text box will then shift (left shift) to the second box, repeating this until all 4 fields are filled - Refer to image Insert.

  3. If the cursor shifts to any element other than the first/rightmost box, it will automatically move back to the rightmost field as inputs are only permitted on that box.

  4. A backspace function should be implemented which deletes the content in the rightmost/first field. Consequently, the fourth field's value will move to the third, the third to the second, and so forth, creating a right shift effect. All elements should follow this deletion pattern - Reference image Delete.

View Screenshot Insert here.

Check out Screenshot Delete here.

Note: The solution must be exclusively created using JavaScript; jQuery is not allowed.

<form>

<input type="text" id="fourth" size="1" maxlength="1" />     
<input type="text" id="third" size="1" maxlength="1" />
<input type="text" id="second" size="1" maxlength="1" />
<input type="text" id="first" size="1" maxlength="1" />  

 <html>
 <head>
</head>
<body>

<form>

 <input type="text" id="fourth" size="1" maxlength="1" />     
 <input type="text" id="third" size="1" maxlength="1" />
<input type="text" id="second" size="1" maxlength="1" />
<input type="text" id="first" size="1" maxlength="1" />  

</form>

<script>
var myInputs = document.getElementsByTagName("input");
var myEditable = document.getElementById("first");
for (var i = 0; i < myInputs.length; i++) {
 myInputs[i].addEventListener("click", function() {
 document.getElementById("first").focus();
 })
}

myEditable.addEventListener("keypress", function(evt) {


if (evt.which >= 48 && evt.which <= 57) {
// Number input detected, initiating LEFT shift

if (myInputs[0].value == "") {
  for (var i = 0; i < myInputs.length - 1; i++) {
    myInputs[i].value = myInputs[i + 1].value;
  }
  myEditable.value = String.fromCharCode(evt.which);
 }
} else {

evt.preventDefault();   // Non-integer inputs prevented in rightmost field
console.log("Incorrect input");
  }
})


 myEditable.addEventListener("keyup", function(evt) {

 if (evt.which == 8) {

 // Implementing backspace feature
 for (var i = myInputs.length - 1; i >= 1; i--) {
  myInputs[i].value = myInputs[i - 1].value;
}
myInputs[0].value = "";
 }
});
</script>

</body>
</html>

One primary issue I am encountering is disabling non-integer inputs specifically in the first/rightmost text field. No JavaScript alert should appear; rather, it should simply reject any non-integer input.

While my current implementation prevents non-integer input in the other text fields, I need guidance on how to restrict such input solely in the first/rightmost field.

Answer №1

It is important to remember to call preventDefault() on the event to ensure proper functionality. Take note of the preventDefault being used in the else statement where console.log("Sorry") is triggered. Check out this JSFiddle

Ensure that all input elements are selected and the editable element is identified by id.
Iterate through the input elements and add an event listener for clicking to focus on the editable element.

Add a keypress event listener on the editable element to handle the input value shift logic based on keycodes.
If the pressed key represents a number, perform leftward shifting of values within inputs.
Otherwise, prevent the default action and log "Sorry".

Include a keyup event listener to handle backspace functionality by shifting input values to the right and clearing the first input.

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

Connecting two COTURN servers for seamless communication

Currently, I have a total of 5 webRTC peers connected through the COTURN server (turnServer1). These peers are all behind symmetric NAT, requiring the use of the TURN server to establish connections. However, due to the media streams with audio and video b ...

Difficulties encountered when attempting to use a background image for shadow effects within a CSS design

I have been learning from a tutorial on how to create a fixed tabless CSS layout, starting from Photoshop and ending with HTML+CSS code. Here is the final example suggested by the tutorial (how it should look like in the end): And this is my own version ...

Puppeteer causes Express to stop listening to incoming requests

As I work on developing a straightforward API that utilizes Puppeteer to execute actions, I encounter an issue where my Express app stops listening once Puppeteer is launched. Below is the script in question: const Apify = require('apify'); cons ...

What is the best way to position a drop-down box in front of images?

After creating a gallery page to showcase website images, I encountered an issue where the images overlapped with the drop-down boxes of my navigation bar. Unfortunately, this means that I am unable to click on the drop-down boxes in order to navigate to o ...

SDTT: "Please ensure that the image field has a value before continuing"

I recently added this code snippet to a LocalBusiness listing (using guidance from this resource): <div itemscope itemtype="http://schema.org/LocalBusiness"> <div itemprop="image" itemscope="" itemtype="http://schema.org/ImageObject"> ...

Guide to creating draggable text on a video with HTML

I have a challenge where I need to overlay text on a video and make it draggable across the entire video. Currently, I am able to display the text over the video successfully, but when I try to drag it and then drop it, the text appears below the video and ...

Checking for an exact value using the includes() method in JavaScript - a comprehensive guide

In order to populate checkboxes based on a string delimited with pipes, I have been using the includes() method. However, I am encountering an issue where items with similar names are both marked as true because they share the same string, even if they are ...

Can someone recommend a streamlined JavaScript algorithm for identifying the unique arrays within a collection of arrays?

Consider the array below: let array = [[1, 2], [1, 2], [3, 4], [5, 6], [2, 1]] I am looking for a way to determine the number of unique arrays in this set. Using the array above as an example, the expected result is 3. How can I achieve this? The code sn ...

Utilizing the index of the .map function in conjunction with internal methods

After running my code, I encountered the following error message: Warning: Encountered two children with the same key, `classroom-1278238`. Keys are required to be unique so that components can maintain their identity during updates. Having non-unique keys ...

Unable to access the jcrop object in order to release it using ajax with jQuery

Hello everybody, I've been struggling with this issue for the past 3 hours and I can't seem to find a solution XD. I have an ajax upload that successfully opens a Twitter Bootstrap modal window upon completion, loads the image, initializes the j ...

Is there a way to display a specific dropdown menu depending on the checkbox that is selected?

I have a bunch of checkbox items, including one labeled nocalls, as well as a couple of dropdownlist boxes. Here are the dropdown boxes: <tr> <td align="right"><FONT class="Arial10"><B>Profile<font color="#ff0000">*</ ...

Streaming video to multiple clients concurrently using NodeJS

We are currently facing an issue with serving a video stream. Due to the fact that HTML5 video tag does not support udp to multicast, we have been attempting to repurpose an existing ffmpeg stream and broadcast it to multiple responses. Unfortunately, thi ...

Navigate through a JavaScript text file one line at a time

There is a text file with the following content: User:root Password:root123 My goal is to read this text file in JavaScript line by line and store it in an array. Then, I want to split each value in the array using a colon (:). Despite trying multiple a ...

What is the best way to retrieve the value of the button that was clicked using JQuery?

Looking to capture the selected value from a dropdown menu in order to execute a database query for rendering the next page. How can I extract only the clicked value from the dropdown menu? The dropdown menu is dynamically generated from the database: ...

Execute code after the CSS has been loaded, but before the images start downloading

My website is experiencing a challenge. Downloading images is taking too long, with the complete website taking around 20 seconds to fully load on my system. A loader is displayed but only hides once the complete website is loaded (after 20 seconds). Whe ...

Clickable Tags within <button> element even in disabled state - exclusive to Webkit

Check out this example to see what I mean. Using $(document).on("click"....), I notice that I am still able to click on elements inside a disabled button. However, this behavior does not happen with $("button").click(.. FIDDLE Does anyone have an explana ...

What is the inability to place a div that is 30% wide alongside another div that is 70% wide, and keep them in a horizontal line?

If I make a div that is 30% wide, and another div that is 70% wide, they do not align horizontally. To fix this, I need to ensure that the combined widths of the two divs are less than 100%. Here's an example of how it can be done: <div id="wrapp ...

Suspend Coontact-Host Upload of Documents

Is there a way to pause or resume uploading, or resume a broken upload using PHP, JavaScript, or jQuery without having to rely on Java, Flash, or C-type programming? Perhaps utilizing PHP socket functions? ...

Troubleshooting a Compatibility Problem Between Django and JavaScript

I am trying to dynamically insert a variable into a URL within the code snippet provided, but I keep encountering an error. function initializeDataTable(id){ var columnSize = $('table th').size(); $('#table').dataTable({ ...

how to use jQuery to hide a flash-containing div without losing its content

Hello, I created a modal with jQuery UI that is displaying in front of a flash movie. However, the HTML content inside the modal appears corrupted. I attempted to hide the movie just before the modal is triggered and make it reappear after closing the mo ...