Move each four-character IT value to a new line

const maxNumLength = 4;
    event = jQuery.Event("keypress")
    event.which = 13
    $('#input').on('input focus keydown keyup', function() {
        const inputValue = $(this).val();
        const linesArray = inputValue.split(/(\r\n|\n|\r)/gm); 
        for (let j = 0; j < linesArray.length; j++) {
            if (linesArray[j].length > maxNumLength) {
                linesArray[j] = linesArray[j].substring(0, maxNumLength);
            }
        }
        $(this).val(linesArray.join(''));
    });

I have implemented the code to move numbers to the next line after every 4 digits, but it does not seem to be working. Can someone please provide guidance on how to fix this issue?

Answer №1

Make sure to check for any line breaks in the input before dividing them into chunks again.

$('#mytext').on('input', function() {
  var value = $(this).val().split( "\n" ).join( "" );   
  var output = getChunks( value, 4 );
  $(this).val(output.join("\n"));
});

function getChunks(str, chunk) {
  var i, j;
  var output = [];
  var array = str.split( "" );
  for (i = 0, j = array.length; i < j; i += chunk) 
  {
    output.push( array.slice(i, i + chunk).join( "" ) );
  }
  return output;
}

Demo

$('#mytext').on('keydown', function(e) {
  if (e.which == 13 )
  {
     e.preventDefault();
     alert( "Enter was pressed" );
     this.blur();
     return false;
  }
});


$('#mytext').on('input', function() {
  var value = $(this).val().split( "\n" ).join( "" );   
  var output = getChunks( value, 4 );
  $(this).val(output.join("\n"));
});

function getChunks(str, chunk) {
  var i, j;
  var output = [];
  var array = str.split( "" );
  for (i = 0, j = array.length; i < j; i += chunk) 
  {
    output.push( array.slice(i, i + chunk).join( "" ) );
  }
  return output;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="mytext" name="text_body"></textarea>

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

Could one harness the power of SO's script for adding color to code within questions?

Similar Question: Syntax highlighting code with Javascript I've observed that Stack Overflow utilizes a script to apply color coding to any code shared in questions and answers, making it resemble how it would appear in an IDE. Is this script pub ...

I am looking to showcase the JSON output on a ReactJS interface

Here is the output of my JSON data I am using the Map function in ReactJS to display elements from a JSON array. I have attempted the code below and encountered an error stating "Cannot read property '_currentElement' of null." Can someone pleas ...

Can I extract JSON data from the AJAX response?

When receiving JSON data, such as in the example below, it is often necessary to separate each value into individual variables: var reviewDate ='2015-06-01T05:00:00Z' var developers ='Ankur Shah,Srikanth Vadlakonda,Tony Liu, Qiuming Jie&ap ...

Is there a way to execute code right before the jQuery submit() function is run?

I'm currently facing an issue with executing codes before a validation function runs in my form. I have tried different methods including referring to How to order events bound with jQuery, but without success. This is the code snippet I am working w ...

After completing the installation of "node-pty" in an electron-forge project on Linux, I noticed that the pty.node.js file is not present. What is the proper way to install node-pty

Following the installation of node-pty, an external module utilized to generate pseudo terminals with Node.js in a boilerplate electron-forge project, I encountered an issue. The error indicated that a core module within node-pty was attempting to import a ...

What is the process for retrieving data from mongoDB and displaying it by year in a single row?

I have received an array of data from MongoDB, which includes id, userName, and date. The date consists of years and months. My goal is to display this data categorized by years. How can I construct a query to the database that will show the data for all y ...

Switch back and forth between two tabs positioned vertically on a webpage without affecting any other elements of the page

I've been tasked with creating two toggle tabs/buttons in a single column on a website where visitors can switch between them without affecting the page's other elements. The goal is to emulate the style of the Personal and Business tabs found on ...

Generate a new entry by analyzing components from a separate array in a single line

I have a list of essential items and I aim to generate a record based on the elements within that list. Each item in the required list will correspond to an empty array in the exist record. Essentially, I am looking to condense the following code into one ...

How to fetch select element within a table by using jQuery

I encountered a situation where I have a table element with a select element inside its td. The id of the table (in this example, it is "table1") could potentially change. So my query is, how can I retrieve the selected option using the table ID in JQuer ...

Error: Attempting to access a property named '_updatedFibers' on an undefined object is not possible due to a TypeError

I encountered the following error: Uncaught TypeError: Cannot read properties of undefined (reading '_updatedFibers') at requestUpdateLane (react-dom.development.js:25411:23) at updateContainer (react-dom.development.js:28810:14) at ReactDOMHydra ...

Switch between individual highcharts by selecting or deselecting checkboxes

One of the challenges I am facing involves manipulating multiple scatter plots created with highcharts. I have a list of checkboxes, each labeled to correspond with legend identifiers in the highcharts. My goal is to create a dynamic functionality so tha ...

Error: The function sendFile does not exist in the method res.status(...)

As a newcomer to this field, I must apologize if my issue has an obvious solution. However, I am encountering the following error: TypeError: res.status(...).sendFile is not a function at app.get (/root/discordtest/server.js:10:19) at callbacks (/ ...

Enhancing TypeScript - Managing Variables within Namespace/Scope

Why is the console.log inside the function correctly logging the object, but after the function returns it logs undefined, failing to update the variable? In addition, when using this within testNameSpace, it returns window. Why is that? namespace testNa ...

Guide to integrating the Google identity services library in a React application

I've encountered an issue with my current code, which has suddenly stopped working: import React, { Component } from "react"; import Auth from "../../helper/auth"; import PropTypes from "prop-types"; import logo from &quo ...

Building Unique Staircases with Three.js Geometry

I have been working on creating a custom three.js geometry for round staircases, but I seem to have made some errors with the vertices and indexes of the steps. Below is an example staircase that utilizes my custom geometry: https://i.sstatic.net/uQXvP.j ...

Implementing various event listeners for asynchronous JavaScript and XML requests (

Struggling to iterate through an ajax query and encountering a problem where the i value always defaults to 1. I'm not very well-versed in js so any suggestions on how to tackle this issue or possibly a better approach would be greatly appreciated. Th ...

Refresh the jQuery Raty choice when clicked (jQuery)

Currently, I am incorporating the jQuery Raty plugin into a jQuery UI dialog to create a questionnaire-style format. Through custom jQuery scripting, I have devised an interactive interface where users are presented with a new question upon each selection ...

What is the reason behind Chrome Dev Tools not automatically adding the parentheses when a method is selected?

In the console of Dev Tools, if you have an object named x with three methods/functions - a(), b(), and c(i, j, k), why doesn't it automatically insert the parentheses, along with the correct spaces for the parameters (similar to eclipse for Java) whe ...

Steps for creating a personalized query or route in feathersjs

I'm feeling a bit lost and confused while trying to navigate through the documentation. This is my first time using feathersjs and I am slowly getting the hang of it. Let's say I can create a /messages route using a service generator to GET all ...

Changing the Div heights in Material UI with grid layout customization

I have a project that requires me to implement material-ui. Is there a way I can adjust the width and height of the div containing the "Sign In With" text (as shown in the first image) to bring the buttons closer to the text? Transformation from this: ht ...