views:

4997

answers:

6

Hi,

I'm looking for a javascript that can limit the number of lines (by line I mean some text ended by user pressing enter on the keyboard) the user is able to enter in textarea. I've found some solutions but they simply don't work or behave really weird. The best solution would be a jquery plugin that can do the work - something like CharLimit, but it should be able to limit text line count not character count.

Thanks in advance.

+2  A: 

The number of visible/display lines for a given block of text would vary with different browsers, fonts used, etc. You'd have to set a specific font and font-size, at a minimum, to be able to semi-reliably count display lines.

UPDATE: I see the edit. Then something like kevchadders code should do fine for you. You'll need js that counts chars and '\r\n's and checks against a user-defined limit. Also, if you don't use his script, make sure you use one that involves either a time interval check and/or the onKeyDown/onKeyUp events of the textarea. This may be why some scripts you have tested seem to "behave strangely".

alphadogg
Looks like empi edited the question on ya ;) Line == "\n"
Crescent Fresh
A: 

I found this link which seems to do it (In IE). Apoligies if you've already looked at this and it isnt suitable.

Also as a though, if different browsers are causing you problems, it might be worth checking for the browser in javascript so that you can tweak to code to behave correctly for each one.

http://www.codingforums.com/archive/index.php/t-71233.html

<html>
<head>
<title>Limit Textarea</title>
<style type="text/css">

textarea{
width:400px;
height:200px
}

</style>
<script type="text/javascript">

var alert_title='Input Restriction';

function limitTextarea(el,maxLines,maxChar){
if(!el.x){
el.x=uniqueInt();
el.onblur=function(){clearInterval(window['int'+el.x])}
}
window['int'+el.x]=setInterval(function(){
var lines=el.value.replace(/\r/g,'').split('\n'),
i=lines.length,
lines_removed,
char_removed;
if(maxLines&&i>maxLines){
alert('You can not enter\nmore than '+maxLines+' lines');
lines=lines.slice(0,maxLines);
lines_removed=1
}
if(maxChar){
i=lines.length;
while(i-->0)if(lines[i].length>maxChar){
lines[i]=lines[i].slice(0,maxChar);
char_removed=1
}
if(char_removed)alert('You can not enter more\nthan '+maxChar+' characters per line')
}
if(char_removed||lines_removed)el.value=lines.join('\n')
},50);
}

function uniqueInt(){
var num,maxNum=100000;
if(!uniqueInt.a||maxNum<=uniqueInt.a.length)uniqueInt.a=[];
do num=Math.ceil(Math.random()*maxNum);
while(uniqueInt.a.hasMember(num))
uniqueInt.a[uniqueInt.a.length]=num;
return num
}

Array.prototype.hasMember=function(testItem){
var i=this.length;
while(i-->0)if(testItem==this[i])return 1;
return 0
};

function set_ie_alert(){
window.alert=function(msg_str){
vb_alert(msg_str)
}
}

</script>
<script language="vbscript" type="text/vbs">

set_ie_alert()

Function vb_alert(msg_str)
MsgBox msg_str,vbOKOnly+vbInformation+vbApplicationModal,alert_title
End Function

</script>
</head>
<body>
<textarea onfocus="limitTextarea(this,6,40)" wrap="off">some text</textarea>
<textarea onfocus="limitTextarea(this,2,10)" wrap="off">some text</textarea>
</body>
</html>
kevchadders
This counts lines separated by '\r\n', not display lines. If I type a massive, run-on paragraph, I will only be subject to the char-count limit. For the first textbox, I'm limited to hitting return 6 times, or typing up 10 40 characters.
alphadogg
yes, I've seen it and was looking for a better solution ;) e.g. i don't know if it would work on mac os.
empi
A: 

did you try the rows attribute?

rows="4"

Slee
This controls the vertical size of the textbox only, not a row limit.
Crescent Fresh
+6  A: 

This might help (probably be best using jQuery, onDomReady and unobtrusively adding the keydown event to the textarea) but tested in IE7 and FF3:

<html>
  <head><title>Test</title></head>
  <body>
    <script type="text/javascript">
      var keynum, lines = 1;

      function limitLines(obj, e) {
        // IE
        if(window.event) {
          keynum = e.keyCode;
        // Netscape/Firefox/Opera
        } else if(e.which) {
          keynum = e.which;
        }

        if(keynum == 13) {
          if(lines == obj.rows) {
            return false;
          }else{
            lines++;
          }
        }
      }
      </script>
    <textarea rows="4" onkeydown="return limitLines(this, event)"></textarea>
  </body>
</html>

*Edit - explanation: It catches the keypress if the ENTER key is pressed and just doesn't add a new line if the lines in the textarea are the same number as the rows of the textarea. Else it increments the number of lines.

marktucks
A: 

This is basically the same as Ivan's answer, using jQuery. I tested it for a project of my own; seems to work fine.

<script type="text/javascript" charset="utf-8">
  $(function() 
  {
    function getLines(id)
    {
      return $('#' + id).val().split("\n").length
    }

  $('#testing').keyup(function() 
  {
    var allowedNumberOfLines = 4;

    if(getLines('testing') > allowedNumberOfLines)
    {
      modifiedText = $(this).val().split("\n").slice(0, allowedNumberOfLines);
      $(this).val(modifiedText.join("\n"));
    }
  });
});
</script>
getLines(id) should be getLines(el) where $('#testing') is sent directly to the getLines function. An easy optimization.
jamtoday
But does this work with automatically wrapped words as you type? Your function relies on newlines only.
acme
A: 

Dear All,

I needs something very similar, but only for a normal text paragraph, not textarea.

I need a Jquery script to truncate a text paragraph by line (not by chart count).

I would like to achieve an evenly truncated text-block. It should have a "more" and "less" link to expand and shorten the text paragraph. My text paragraph is wrapped in a div with a class, like this:

<div class="content">
<h2>Headline</h2>
<p>The paragraph Text here</p>
</div>

Many thanks for any tips!

Ben

Bento Graphic