Tally the lines in the textarea

I have a textarea that allows users to input up to 16 lines of text. I created a directive for this purpose, and it works well when the user hits the enter key.

However, I also want to restrict the input to only 16 lines, even if the user enters a very long text that wraps into multiple lines without hitting enter.

The reason behind this question is that I have a digital postcard where users can add a personalized message. The postcard has fixed dimensions, so the textarea should reflect these dimensions by limiting the text to no more than 16 lines.

Is it possible to achieve this using JavaScript?

Here is my current code:

HTML

<textarea placeholder="Enter text" rows="16" ng-trim="false" id="message-textarea" maxlines="16" maxlines-prevent-enter="true"></textarea>

JS Directive

app.directive('maxlines', function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, elem, attrs, ngModel) {
      var maxLines = 1;
      attrs.$observe('maxlines', function(val) {
        maxLines = parseInt(val);
      });
      ngModel.$validators.maxlines = function(modelValue, viewValue) {
        var numLines = (modelValue || '').split("\n").length;
        var diffLines = maxLines - numLines;
        scope.$emit('cliked-from-directive-maxlines', {diffLines});
        return numLines <= maxLines;
      };
      attrs.$observe('maxlinesPreventEnter', function(preventEnter) {
        // if attribute value starts with 'f', treat as false. Everything else is true
        preventEnter = (preventEnter || '').toLocaleLowerCase().indexOf('f') !== 0;
        if (preventEnter) {
          addKeypress();
        } else {
          removeKeypress();
        }
      });

      function addKeypress() {
        elem.on('keypress', function(event) {
          // test if adding a newline would cause the validator to fail
          if (event.keyCode == 13 && !ngModel.$validators.maxlines(ngModel.$modelValue + '\n', ngModel.$viewValue + '\n')) {
            event.preventDefault();
          }
        });
      }

      function removeKeypress() {
        elem.off('.maxlines');
      }

      scope.$on('$destroy', removeKeypress);
    }
  };
});

Answer №1

As far as I am aware, it is not possible to limit the number of lines on a textarea. One alternative would be to use 16 separate single-line inputs and automatically move to the next row when the character limit per line is reached.

Answer №2

Give this a shot

function implementKeypress() {
   var maxLines = 16;
   element.on('keypress', function(event) {
        var currentLines = element.val().split("\n").length;
        if(event.keyCode == 13 && currentLines >= maxLines) {
            return false;
        }
    });
  });
}

Answer №3

Here is a code snippet that demonstrates how you can achieve a specific text limit in a textarea:

JavaScript

$(".limit").on("input", function(evt) {
  var $limit = $(this);
  var limit = this;
  if($limit.innerHeight() !== limit.scrollHeight) {
    $limit.val($limit.data("before"));
    evt.preventDefault();
    return false;
  } else {
    $limit.data("before", $limit.val());
  }
}).each(function(index, el) {
  $(el).data("before", $(el).val());
});

HTML

<textarea class="limit" rows="10"></textarea>

CSS

.limit {
  max-width: 300px;
  min-width: 300px;
  resize: none;
  overflow: hidden;
}

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

"Autodesk Viewer: Unlocking the Power of Programmatic Camera Y-Axis Reversal

I have been utilizing the markups core extension to retrieve and restore the viewer state, which has been successful, except for a problem with inversion (only in 3D). When a client interacts with the y-axis specifically, causing the model to flip to revea ...

Is there a way to identify if you are at the bottom row of a column defined by CSS styling?

I have implemented the new CSS-style column to divide a single unordered list into multiple columns. Now, I am trying to figure out how to target the last element in each column using JavaScript or CSS. Here is my HTML: <ul> <li /> <li ...

Is there a replacement for findIndex in Internet Explorer?

I am currently working on a code snippet for smooth navigation scroll to different sections. var lastId; var topMenu = $(".community-nav"); var topMenuHeight = topMenu.outerHeight() - 19; if(window.matchMedia("(max-width: 768px)").matches) ...

Show a loading icon as the synchronous Ajax request is being sent

Seeking a way to show a spinner while making a synchronous Ajax request to fetch data from the server. Acknowledging that asynchronous mode is preferred, but not permitted in this case. Aware that a sync ajax request can cause browser blocking. An attemp ...

Encountering NaN values in JavaScript arrays

I'm facing an issue with my HTML code that is supposed to make ball(s) bounce around the canvas. However, when I set the arrays storing the coordinates to random positions and test with alert("Co-ordinates " + (cirX[i]) + " x " + (cirY[i]));, it retur ...

What mistake am I making with arrays?

My understanding of JavaScript and Node.JS is still developing, so I'm puzzled as to why I'm receiving NaN when using this expression: var aUsersBetted = {}; aUsersBetted['1337'] += 200000; logger.debug(aUsersBetted['1337']); ...

The footer seems to be losing its stickiness and not staying at the bottom when I

My goal is to create a sticky footer for my webpage. Once you click the add new sports button, a drawer slides out and the footer remains fixed at the bottom. However, as I scroll down the page, the footer moves up instead of staying in place. I have tried ...

What's the Hold-Up with IntersectionObserver in Brackets?

As a novice in the world of web development, I have been utilizing Brackets as my main tool. Recently, I've encountered a few hurdles specifically related to javascript. One issue I'm facing is trying to implement lazy loading on a div containing ...

Troubleshooting npm audit error involving loadVirtual and ENOLOCK

➜ npm safety check npm ERR! code ENOLOCK npm ERR! safety check This operation requires an existing lockfile. npm ERR! safety check Please generate one using: npm i --package-lock-only npm ERR! safety check Original error: loadVirtual needs a preexistin ...

Upon the completion of the page loading, the function will be called immediately after the controller has provided the

I am facing an issue where I am trying to call a computed property upon page creation, but it is giving an error stating that it cannot read the data for 'undefined'. This is because the data I require is not fully loaded yet. However, when I del ...

Utilizing Jquery Validation plugin for Error messages displayed through Bootstrap 5.x popovers

I'm currently struggling to find the correct solution for integrating the jQuery validation plugin with Bootstrap 5.x version popovers. Can anyone offer assistance? ...

What is the best way to center a form element and an image link vertically within a div?

I'm having trouble aligning a search form and an image link within a div. I've attempted using 'display:inline', which did place them on the same line, but not in the way I wanted. I also experimented with adjusting width, float, and pa ...

jQuery can be used to deactivate the submit button

I am trying to prevent users from clicking the submit button multiple times on my form. I attempted to do this using jQuery as shown below: $('form').submit(function() { var formId = this.id; if (formId != ''){ $(&apo ...

Is CDATA insertion automatic in JavaScript within Yii framework?

Currently I am working with Yii and have noticed that whenever I insert any JavaScript code, it is automatically encapsulated in CDATA. I am curious as to why this is happening. Will there be any issues if I were to remove the CDATA tags, considering that ...

Sharing data from a Provider to a function in React can be done through various methods

After developing an NPM library that contains various utility functions, including one for calling endpoints, I encountered a roadblock when trying to set the Axios.create instance globally. Initially, my idea was to create a Provider and establish a cont ...

One possible solution to the error of being unable to set headers after they have already been sent to the client is to ensure that the response is returned

Currently, I am working with expressJS and the following is a snippet of my code in the controller: Within the file readstream, there is a condition check that needs to be met for proper data format. If this condition is not satisfied, I do not want to co ...

I'm having trouble importing sqlite3 and knex-js into my Electron React application

Whenever I try to import sqlite3 to test my database connection, I encounter an error. Upon inspecting the development tools, I came across the following error message: Uncaught ReferenceError: require is not defined at Object.path (external "path ...

Use Javascript to deactivate the mouse cursor and rely solely on the keyboard cursor for navigation

I am facing an issue with a div that contains a textarea. The cursor is automatically positioned at the beginning of the text within the textarea. I would like to disable the mouse cursor when hovering over the textarea but still be able to navigate within ...

The dropdown menu is not able to retrieve information from the secondary database

I have been encountering multiple challenges while working on a web-based dynamic form that I am developing. My current major issue is with populating the second #bodytype dropdown based on the selection made in the first, #bodyman, dropdown. Subsequently ...

Issue arising with data exchange between components using data service in Angular 5

Utilizing data service to share information between components has presented a challenge for me. References: Angular: Updating UI from child component to parent component Methods for Sharing Data Between Angular Components Despite attempting the logic o ...