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

Troubleshooting the issue of CSS animations activating twice and causing a flickering effect specifically in the Firefox browser

I am facing an issue with CSS animations in Firefox. When I try to slide in some radio buttons upon clicking a button, the animation seems to be firing twice in Firefox while it works fine in Chrome. I have attempted several solutions but haven't been ...

Ways to retrieve every element inside a specific div container

Is there a way to select all elements inside a div except for specific ones? For example, consider the following structure: <div id="abc"> <div class="def"> sagar patil</div> <div class="pqr"> patil</div& ...

Using jQuery to load the center HTML element

So here's the plan: I wanted to create a simple static website with responsive images that load based on the browser width. I followed some suggestions from this link, but unfortunately, it didn't work for me. I tried all the answers and even a ...

The server encountered an unexpected error while processing the request, possibly due to a

My JavaScript file includes an interval function that calls the following code: setInterval(function() { $.getJSON('/home/trackUnreadMsgs', function(result) { $.each(result, function(i, field) { var temp = "#messby" + result[i].from; ...

Is there a way to horizontally align my navigation bar links with CSS while maintaining grey borders on the sides?

What is the best way to center my navigation bar links using CSS without losing the grey sides? Both Blogs and History have dropdown menus. Check out this screenshot: (source: gyazo.com) CSS: .navbar ul { list-style: none; margin: 0; pad ...

What steps are involved in creating a table using Bootstrap framework?

Hey there! I need your expertise on how to create a specific layout using bootstrap: codepen.io/anon/pen/bqJdQJ <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <div cl ...

Integrate an item into the request body utilizing the $.load() function in jQuery

Currently, I am using a POST request via jQuery's $.load function to retrieve data to display in a window. This is what I am currently doing: var testObject = { thing1: 'data1', thing2: 'data2', thing3: &a ...

"Implementing JavaScript Validation for Textboxes: A Step-by-Step Guide

I need some help with restricting the input of a textbox within a gridview to only 'X' or 'O'. I am not very familiar with javascript, so any guidance on how to accomplish this would be greatly appreciated. It's worth noting that t ...

Effective methods for eliminating timezone in JavaScript

I need to display the time and format {{transaction.submitTime | date:'yyyy-MM-dd HH:mm:ss Z'}} Currently, it displays 2015-04-23 02:18:43 +0700 However, I would like to show the time without +0700, where the hour will be incremented by 7. Is ...

"Troubleshooting issues with retrieving data from database using Ajax and

Help needed! I'm facing issues with a select code while using ajax. The codes seem to be incorrect and not working as intended. Here is the snippet of the problematic code: <?php require_once 'config/dbconfig.php'; if (isset($_REQUE ...

Retrieve JSON data from an external website

I am looking to display the number of players currently playing on a different poker website on my own site. The necessary data is provided in JSON format by this link (tournaments.summary.players). I have tried using a .getJSON request, but it seems like ...

Tips for dynamically updating values when input numbers are modified using JavaScript

Check out this amazing tip calculator on netlify. I successfully built it using html, scss, and javascript without relying on any tutorials. Despite taking longer than expected due to being a beginner, I am proud of the outcome. Now, I need some assistanc ...

The variable "vue" is not properly defined within the instance, yet it is being called

I'm currently working on a Vue app and encountering an issue. The onScroll function is working correctly, but when I click the button component to trigger the sayHello function, I receive an error message. The error states: "Property or method &apo ...

What is the best way to display input fields only if the previous input has a valid value?

My challenge involves creating a form with 3 to 10 text input fields. Initially, the form will display only 3 inputs (minimum). I am looking for an efficient way to dynamically show additional input rows as each previous row is filled out with a valid val ...

How do I prevent a specific word from being removed in a contenteditable div using JavaScript?

Attempting to create a terminal-like experience in JS, I am looking to generate the word 'current source, current location' (e.g., admin@ubuntuTLS~$: ~/Desktop) at the beginning which cannot be removed. Also, I want to prevent the caret from bein ...

Incorporate socket.io into multiple modules by requiring the same instance throughout

I am feeling a bit lost when it comes to handling modules in Node.js. Here's my situation: I have created a server in one large file, utilizing Socket.io for real-time communication. Now, as my index.js has grown quite big, I want to break down the ...

Maximizing the potential of image srcset in HTML5

After configuring the img srcset as shown below: <img srcset="http://via.placeholder.com/320x150 320w, http://via.placeholder.com/480x150 480w, http://via.placeholder.com/800x150 800w" src="http://via.placeholder.com/8 ...

Applying a dynamic translate3d transformation on the ::after element using CSS3

My current challenge involves manipulating a pseudo ::after element using translate3d If I hardcode the values, it's straightforward: div::after { ... transform: translate3d(40px, 40px, 0); } Now, I want to dynamically set the value for the ...

What is the process of sending a file to a server and storing it in a MySQL database?

Currently, I am exploring the process of enabling users to upload images of specific dimensions (468px by 60px) to a designated directory on my server, such as example.com/banners. Subsequently, the URL link to these uploaded banners will be stored in a ...

Re-sorting with _.sortBy() eliminates additional 0s from decimal values (transforming 0.10 to 0.1 and beyond)

Here is an array that needs to be sorted: var baseBetAmount = [ { val: 'OtherBaseBet', text: 'Other' }, { val: 0.10, text: '$0.10' }, { val: 0.20, text: '$0.20' }, { val: 0.50, text: ...