最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Max lines textarea - Stack Overflow

programmeradmin1浏览0评论

I have found some scripts that limit the lines used in a textarea like this:

 $(document).ready(function(){

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

        $('#rev').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', '');
            } 
        }); 

It works fine when you hit enter and limits it to 10 .But the problem occurs when you type sentences that are so long they automatically go to a new line without the \n and when you copy paste a text, then it fails to limit the lines used.

does anyone know how to fix this.

Important: solution needs to work for a textarea

I have found some scripts that limit the lines used in a textarea like this:

 $(document).ready(function(){

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

        $('#rev').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', '');
            } 
        }); 

It works fine when you hit enter and limits it to 10 .But the problem occurs when you type sentences that are so long they automatically go to a new line without the \n and when you copy paste a text, then it fails to limit the lines used.

does anyone know how to fix this.

Important: solution needs to work for a textarea

Share Improve this question edited Apr 9, 2014 at 13:24 Poorya Mohammadi asked Mar 29, 2014 at 12:58 Poorya MohammadiPoorya Mohammadi 7511 gold badge8 silver badges18 bronze badges 6
  • 1 have you tried calculating the line-height instead? – benomatis Commented Mar 29, 2014 at 13:06
  • I've tried something, have a look at my answer... – benomatis Commented Mar 29, 2014 at 14:50
  • what do you want it to do when you paste text, do you want the text cut off anything that goes beyond the limit...? – benomatis Commented Mar 29, 2014 at 19:22
  • ok, I updated my answer, check it out! And don't forget to accept it as a correct answer (big checkmark below the voting buttons), if you think it is the one! ;) – benomatis Commented Mar 29, 2014 at 21:27
  • not sure about you, but I haven't found anything solving this with a textarea specifically, although I'm generally quite good at searching... any reasons why you absolutely need to use a textarea? – benomatis Commented Apr 10, 2014 at 5:50
 |  Show 1 more comment

3 Answers 3

Reset to default 10 +50

You could try doing it using this logic:

JS :

var limit = 3; // <---max no of lines you want in textarea
var textarea = document.getElementById("splitLines");
var spaces = textarea.getAttribute("cols");

textarea.onkeyup = function() {
   var lines = textarea.value.split("\n");

   for (var i = 0; i < lines.length; i++) 
   {
         if (lines[i].length <= spaces) continue;
         var j = 0;

        var space = spaces;

        while (j++ <= spaces) 
        {
           if (lines[i].charAt(j) === " ") space = j;  
        }
    lines[i + 1] = lines[i].substring(space + 1) + (lines[i + 1] || "");
    lines[i] = lines[i].substring(0, space);
  }
    if(lines.length>limit)
    {
        textarea.style.color = 'red';
        setTimeout(function(){
            textarea.style.color = '';
        },500);
    }    
   textarea.value = lines.slice(0, limit).join("\n");
};

Here is the UPDATED DEMO

Well, I couldn't figure out how to calculate the height of only the text inside a textarea, so I used a contenteditable div instead. Hope you like this solution.

HTML

<div id="container">
    <div id="rev" contenteditable="true"></div>
</div>

CSS

#container {
    height:100px;
    width:300px;
    cursor:text;
    border:1px solid #000
}
#rev {
    line-height:20px;
    outline:none
}

JS

$(document).ready(function () {
    $('#container').click(function() {
        $('#rev').focus();
    });

    var limit = 3;
    var lineHeight = parseInt($('#rev').css('line-height'));

    $('#rev').keydown(function (e) {
    var totalHeight = parseInt($('#rev').height());
    var linesUsed = totalHeight / lineHeight;

        if (e.keyCode == 13 && linesUsed >= limit) {
            $('#rev').css('color', 'red');
            return false;
        } else {
            $('#rev').css('color', '');
        }
    });
});

HERE IS A DEMO YOU CAN FIDDLE WITH

MAJOR EDIT

Following the OP pointing out I actually forgot to address the most important, I updated my code. I basically removed the check for the enter key and allowed the delete and backspace keys in case the text goes over the limit as follows. You may have to fiddle around with it a little to make it fit to your exact needs.

$(document).ready(function () {
    $('#container').click(function() {
        $('#rev').focus();
    });

    var limit = 3;
    var lineHeight = parseInt($('#rev').css('line-height'));

    $('#rev').keydown(function (e) {
    var totalHeight = parseInt($('#rev').height());
    var linesUsed = totalHeight / lineHeight;

        if (linesUsed > limit) { // I removed 'e.keyCode == 13 &&' from here
            $('#rev').css('color', 'red');
            if (e.keyCode != 8 && e.keyCode != 46) return false; // I added this check
        } else {
            $('#rev').css('color', '');
        }
    });    
        
    // I added the following lines
    $('#rev').on('paste', function () { 
        if (linesUsed > limit) {
            $('#rev').css('color', 'red');
            if (e.keyCode != 8 && e.keyCode != 46) return false;
        } else {
            $('#rev').css('color', '');
        }
    });
});

UPDATED DEMO HERE

It's too much work to try to figure how many lines based on the number characters in each line and the textarea width (does the textarea have wrapping off or not? font size, different letter widths, spaces, etc...). The easiest way is to have two textareas (one visible and one not - height set to 0) with the same width and font styles and check the scroll height of the invisible textarea.

Here is an example http://jsfiddle.net/SKYt4/1/

HTML

<textarea id="visible_textarea"></textarea>
<textarea id="hidden_textarea"></textarea> <!-- hidden by setting the height to 0 -->
<div id="used_lines"></div>

CSS

textarea {line-height:16px; /* line height to calculate number of lines */
    width:150px; /* need to match width */}
#hidden_textarea {height:0px;
    padding:0px;
    border:none;
    margin:0px;
    opacity:0;}

JavaScript

$('#visible_textarea').keyup(function(){
    $('#hidden_textarea').val(this.value);
    // checking how many lines
    var lns = Math.ceil(document.getElementById('hidden_textarea').scrollHeight / parseInt($('#hidden_textarea').css('line-height')));

    if (lns > 10) {
         $('#used_lines').css('color', '#ff0000');
    }
    else {
        $('#used_lines').css('color', '');
    }

    $('#used_lines').html(lns+' lines');
});


$('#visible_textarea').change(function(){
    $(this).keyup();
});
发布评论

评论列表(0)

  1. 暂无评论