28

Using jQuery I would like to:

  • Limit the number of lines a user can enter in a textarea to a set number
  • Have a line counter appear that updates number of lines as lines are entered
  • Return key or \n would count as line
$(document).ready(function(){
  $('#countMe').keydown(function(event) {
    // If number of lines is > X (specified by me) return false
    // Count number of lines/update as user enters them turn red if over limit.

  });   
});


<form class="lineCount">
  <textarea id="countMe" cols="30" rows="5"></textarea><br>
  <input type="submit" value="Test Me">
</form>

<div class="theCount">Lines used = X (updates as lines entered)<div>

For this example lets say limit the number of lines allowed to 10.

user202729
  • 3,358
  • 3
  • 25
  • 36
chainwork
  • 2,890
  • 4
  • 30
  • 29
  • 2
    possible duplicate of [Limiting number of lines in textarea](http://stackoverflow.com/questions/556767/limiting-number-of-lines-in-textarea) – PetersenDidIt Jun 28 '11 at 03:15
  • Thanks Petersen, actually I did review that and did not find the complete answer I was looking for. – chainwork Jun 28 '11 at 15:16

5 Answers5

53

html:

<textarea id="countMe" cols="30" rows="5"></textarea>
<div class="theCount">Lines used: <span id="linesUsed">0</span><div>

js:

$(document).ready(function(){

    var lines = 10;
    var linesUsed = $('#linesUsed');

    $('#countMe').keydown(function(e) {

        newLines = $(this).val().split("\n").length;
        linesUsed.text(newLines);

        if(e.keyCode == 13 && newLines >= lines) {
            linesUsed.css('color', 'red');
            return false;
        }
        else {
            linesUsed.css('color', '');
        }
    });
});

fiddle: http://jsfiddle.net/XNCkH/17/

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
  • 1
    Samuel Liew, thank you so very much! I'm sure this will be helpful to a lot of people. – chainwork Jun 28 '11 at 15:21
  • 1
    The return false does not seem to be working when I paste in a large number of lines. Is there a way this can be modified to ensure a user cannot submit the form if the number of allowed lines has been exceeded? – chainwork Jun 28 '11 at 16:04
  • 1
    You could use the 'paste' event on the text area – codinghands Apr 30 '14 at 15:07
  • 1
    Is there anyway to convert this to an on "click" (button) method? – Sanya Feb 27 '15 at 16:15
2

Here is little improved code. In previous example you could paste text with more lines that you want.

HTML

<textarea data-max="10"></textarea>
<div class="theCount">Lines used: <span id="linesUsed">0</span></div>

JS

jQuery('document').on('keyup change', 'textarea', function(e){

        var maxLines = jQuery(this).attr('data-max');        
        newLines = $(this).val().split("\n").length;

        console.log($(this).val().split("\n"));

        if(newLines >= maxLines) {
            lines = $(this).val().split("\n").slice(0, maxLines);
            var newValue = lines.join("\n");
            $(this).val(newValue);
            $("#linesUsed").html(newLines);
            return false;
        }

    });
2

For React functional component that sets new value into state and forwards it also to props:

const { onTextChanged,  numberOfLines, maxLength } = props;
const textAreaOnChange = useCallback((newValue) => {
        let text = newValue;
        if (maxLength && text.length > maxLength) return
        if (numberOfLines) text = text.split('\n').slice(0, numberOfLines ?? undefined)
        setTextAreaValue(text); onTextChanged(text)
    }, [numberOfLines, maxLength])
Daniel
  • 21
  • 2
1

For the React fans out there, and possibly inspiration for a vanilla JS event handler:

onChange={({ target: { value } }) => {
    const returnChar = /\n/gi
    const a = value.match(returnChar)
    const b = title.match(returnChar)
    if (value.length > 80 || (a && b && a.length > 1 && b.length === 1)) return
    dispatch(setState('title', value))
}}

This example limits a textarea to 2 lines or 80 characters total.

It prevents updating the state with a new value, preventing React from adding that value to the textarea.

mattdlockyer
  • 6,984
  • 4
  • 40
  • 44
0

A much ugly , but somehow working example specify rows of textarea

<textarea rows="3"></textarea>

and then in js

   $("textarea").on('keydown keypress keyup',function(e){
       if(e.keyCode == 8 || e.keyCode == 46){
           return true;
       }
       var maxRowCount = $(this).attr("rows") || 2;
        var lineCount = $(this).val().split('\n').length;
        if(e.keyCode == 13){
            if(lineCount == maxRowCount){
                return false;
            }
        }
        var jsElement = $(this)[0];
        if(jsElement.clientHeight < jsElement.scrollHeight){
            var text = $(this).val();
            text= text.slice(0, -1);
            $(this).val(text);
            return false;
        }

    });
Alexandr Sargsyan
  • 656
  • 1
  • 6
  • 21