Limit rows in HTML5 textarea

11,077

I think you can do this with pure HTML.

<textarea cols="20" rows="5" wrap="hard" maxlength="100">

The wrap="hard" means that once the user has reached the end of the line - in this case, 20 characters - a newline will be inserted.

Once the user has reached 100 characters - the same as filling in 5 lines with 20 characters - no more input will be allowed.

Now, this doesn't stop someone from adding 10 lines with 10 characters - but does it get close to what you want to do?

Share:
11,077
panagulis72
Author by

panagulis72

Updated on June 04, 2022

Comments

  • panagulis72
    panagulis72 almost 2 years

    I'm looking for a solution to a problem, but I'm not able to find it. It could be in AngularJS or in Javascript (then I'll translate it in AngularJS). The problem is that I have to limit the rows of a simple textarea. The attribute 'rows=x' of HTML5 limit just the view. I have to limit the lines. The problem is that even if graphycally the lines go down, the components looks at it as a unique line. The user has to press ENTER to create a new line. But, I have to limit the lines. I did this directive:

    angular.module('app').directive('maxlines', function (): any {
    return function (scope: any, element: any, attrs: any) {
        element.bind("keydown keypress", function (event: any) {
    
            if (event.which === 13) {
                var text = element.val(),
                    numberOfLines = (text.match(/\n/g) || []).length + 1,
                    maxRows = parseInt(element.attr('rows'));
    
                if (event.which === 13 && numberOfLines === maxRows) {
                    return false;
                }
            }
        });
    };
    });
    

    It works if I press ENTER, but it doesnt work if I continue to write withouth press enter.

    • Alexis
      Alexis over 5 years
      Textarea can be resized and the line length will be different. I suggest you to block the resize of the textarea and to limit the number of character of it to have only on line.
    • panagulis72
      panagulis72 over 5 years
      I used css to block the size. Yeah I know I can limit character and this would be the best solution, but the break line (\n) is considered as 1 character, so if I set 800 characters, the user can press 799 times ENTER and then write a word in the last line
    • Alexis
      Alexis over 5 years
      Then block the enter action
    • panagulis72
      panagulis72 over 5 years
      I have to let the user press enter to create a white space for a new paragraph :/
    • Alexis
      Alexis over 5 years
      Ok got it, then only authorize the enter if the last character is not a break line.
  • panagulis72
    panagulis72 over 5 years
    Yeah i tried too wrap hard! And it goes in new line, but it is considered (from my angularJS directive) as a unique line, so it go in a new line just graphically unfortunatly