Looking for a way to limit the number of characters allowed per line in a textarea using jQuery

I have the following HTML textarea:

<textarea name="splitRepComments" cols="20" rows="3" ></textarea>

I have implemented a maxlength restriction using jQuery with the following function:

var max = 100;
$('#splitRepComments').bind("keypress", function(e) {


    if (e.which < 0x20) {
        // e.which < 0x20, then it's not a printable character
        // e.which === 0 - Not a character
        return; // Do nothing
    }
    if (this.value.length == max) {
        e.preventDefault();
    } else if (this.value.length > max) {
        // Maximum exceeded
        this.value = this.value.substring(0, max);
    }
});

$('#splitRepComments').bind("paste", function(e) {


    setTimeout(function() {

        var e = jQuery.Event("keypress");
        e.which = 50; // # Some key code value
        $('#splitRepComments').trigger(e);
    }, 100);

});

My challenge is that I need users to enter only 10 characters in each row (line) and then move to the next line.

This function should also adhere to the maxlength restriction of the textarea.

I have attempted a solution from SO, but it does not move input to the next line.

You can view my JSFiddle example for reference.

Answer №1

Check out this code snippet:

    const maxLength = 100;
    const charactersPerLine = 10;

    $("textarea[name='splitRepComments']").bind("keypress", function(e) {

        if (e.which < 0x20) {
            // Ignore non-printable characters
            return; 
        }
        
        let length = this.value.length - ((this.value.match(/\n/g)||[]).length);
        
        if (length === maxLength) {
            e.preventDefault();
        } else if (length > maxLength) {
            // Truncate the input if it exceeds the limit
            this.value = this.value.substring(0, maxLength);
        }
        
        if (length % charactersPerLine == 0 && length !== 0 && length < maxLength) {
            $(this).val($(this).val() + '\n');
        }

    });

Answer №2

Provided below is a plain JavaScript solution with comments for each statement:

var adjustTextAreaSize = function adjustTextAreaSize(fieldId, cols, rows){ 
    // Retrieve textarea text value 
    var value = document.getElementById(fieldId).value; 
    // Save current cursor position (useful for mid-text typing) 
    var currentPosition = document.getElementById(fieldId).selectionStart; 
    // Array to store separate text lines 
    var lines = []; 
    // Remove newline characters and limit the text based on number of rows 
    value = value.split("\n").join(""); 
    if(rows){ 
      value = value.substr(0, cols * rows); 
    } 
    // Check if text length exceeds specified columns 
    if(value.length > cols){ 
      // Divide the text into lines based on column length 
      for(var i = 0; i < value.length; i += cols){ 
        lines.push(value.substr(i, cols)); 
      } 
      // Reconstruct the text by joining the lines 
      document.getElementById(fieldId).value = lines.join("\n"); 
      // Reset cursor position to original location 
      document.getElementById(fieldId).selectionStart = document.getElementById(fieldId).selectionEnd = currentPosition; 
    } 
    // Handle scenarios where text length is less than or equal to max characters per line 
    else if(value.length < cols){ 
      // No action needed 
      return; 
    } 
    else{ 
      // Move to next line 
      document.getElementById(fieldId).value += "\n"; 
    } 
  };

Usage : Include directly in HTML using input event (e.g., 35 characters per line maximum for 6 lines)

<textarea id="myTextArea" cols="70" rows="20" style="resize: none" oninput="adjustTextAreaSize(this.id, 35, 6);"></textarea> 

Note: It's advisable to test this solution with caution when resizing the 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

Switch button for updating text, icon, and displaying search bar

Having trouble with a header and navigation bar setup. The goal is to have a search button that toggles between "Search" and "Close Search" when clicked, while also opening the search bar below the navigation. I've experimented with different methods ...

Modifying the default value setting in MUI Datepicker

Currently, I am utilizing version @mui/x-date-pickers ^6.17.0. Here is the custom date picker I am using: https://i.stack.imgur.com/k8nF1.png Upon clicking the input field, the placeholder switches and a value gets appended. However, modifying the input ...

Manipulate classes using jQuery to add or remove them

Is there a way to toggle classes on click using jQuery without affecting certain elements? I want to be able to switch between .one and .two when clicking on .other-class.one, while .other-class.two should remain unaffected. My current code is only parti ...

Exploring Three.js: The challenge of loading multiple material objects

I am currently using three.js and facing an issue while loading multiple material objects. The problem arises when I rotate the code, causing unexpected behavior with the second material object. Ideally, I want the first material object [cubeMaterial] to r ...

Make sure to save the data in a file correctly by utilizing JSON.stringify before storing

When I use this code snippet: function item(name, number){ this.name = name; this.number = number; } var item1 = new item('a',1); var item2 = new item('b',2); var box1 = [item1,item2]; console.log(box1); var box2 = JSON.strin ...

The Nodejs express static directory is failing to serve certain files

Hello everyone, I'm currently working on a project using NodeJs, Express, and AngularJS. I've encountered an issue where my page is unable to locate certain JavaScript and CSS files in the public static folder, resulting in a 404 error. Strangely ...

Tips for locating and substituting a string in Javascript

Is there a way to locate a particular word within a string and substitute it using JavaScript? For instance Here is a lengthy sentence I want to locate the word "sentence" and modify it to "phrase", resulting in: Here is a lengthy phrase ...

Can you override CSS background image styles to ensure both images are loaded?

Suppose there are 2 CSS styles that assign background images to an element, and one style overrides the other. In this scenario, will both images be downloaded by the browser or just the overriding one? I am asking this because I recently participated in ...

trouble with phonegap javascript ajax integration

I'm new to app development and I've been trying to create a mobile app using PhoneGap. I have a remote shared server that contains a MySQL table. My goal is to sign up a user, then send the data via JavaScript and AJAX to a PHP server page that w ...

Tips for stopping execution in Discord.js if the user no longer exists?

I'm currently working on a discord bot and encountered a minor issue. I am using "messageReactionRemove" and "messageReactionAdd" to manage certain roles by removing or adding them, but the problem arises when a user leaves the server. When this happe ...

Could anyone clarify the workings of the async function in this specific useEffect situation?

Within a child component, there is an onClick event: onClick={()=>{ //2. an image is clicked, and the choice is added to the choiceOrder state, and then a jsonupdate is called -- 3. in ChooseBy.js //onclick, add or remove the choice choosebyprop ...

What could be causing the issue of my navbar text not changing color using CSS?

Despite several attempts, I am unable to change the color of the hyperlinks in blue or purple using the HTML and CSS below. Can anyone point out what I might be missing? nav ul { /* Navbar unordered */ list-style: none; text-align: center; backgr ...

Leveraging promises in conjunction with mongoose operations

I'm new to using promises in conjunction with mongoose query functions such as find() and findById(). While everything seems to be functioning correctly, I am unsure if the way I am chaining then is the proper approach. The goal of utilizing promises ...

a dedicated TypeScript interface for a particular JSON schema

I am pondering, how can I generate a TypeScript interface for JSON data like this: "Cities": { "NY": ["New York", [8000, 134]], "LA": ["Los Angeles", [4000, 97]], } I'm uncertain about how to handle these nested arrays and u ...

The Jsoup function for sending data does not yield any results

Can someone assist me with sending data to a form in this format? <form id="money" action="" method="post"> <input id="user" type="text" placeholder="Username" maxlenght="10" name="user"></input> <div class="select"> <select id= ...

Exploring the Power of Ajax in Struts2

Recently, I started learning about Struts and Ajax. I attempted to create a webpage similar to Gmail, where users enter their username first and then proceed to enter their password. Despite trying out various plugins like Dojo, jQuery, and Jason jars, I ...

The conditional statement for ajax is malfunctioning

I am encountering an issue with some ajax coding. The if condition is not working as expected - whenever the program runs, only the else statement gets executed even when the if statement should be satisfied. <script type="text/javascript> funct ...

Include a class in ul > li elements upon page load in Angular4

I attempted to add a class to each "li" element in an Angular4 page, but the class was not applied. Here is the relevant HTML code: <ul class="pagination"> <button class="previous" (click)="previous()">Previous</button> <button ...

Does Less undergo a compilation process in a single pass?

Does Less execute a single pass on the files, or does it perform multiple passes? I am particularly worried about what will happen if I include another file that redefines variables and mixins. Will the generated output use the original values, or will it ...

Has the Angular 2 community established a standardized ecosystem?

As a developer specializing in Angular 1, I am now eager to dive into the world of Angular 2. However, navigating through the changes and rewrites can feel like traversing a confusing maze. All of the comprehensive guides I have come across date back to l ...