Link to home
Start Free TrialLog in
Avatar of CodeHead
CodeHead

asked on

Counting the lines in textarea

I need to be able to limit the amount of characters and line breaks in a textarea box.  So I might have criteria where the user should only type in 4 lines, 250 characters, or a combination of both.  I am assuming that if the person runs on with a sentence without hitting the enter key that after 70 characters I will consider that a new line.  

Avatar of fritz_the_blank
fritz_the_blank
Flag of United States of America image

This takes care of the character issue--just pass the name of the form and field (i.g. form1.text1) ast the lclObject, the maximum number of characters for lclMaxLength, and some user-friendly name for the field for lclCaption.

function textlength(lclObject,lclMaxlength,lclCaption)
{

var lengthvar=0

lengthvar = eval("document.other." + lclObject + ".value.length");
if (lengthvar >lclMaxlength)
     {
     alert("Please limit your response for " +lclCaption + " to approximately " + lclMaxlength/6 +" words!");
     eval('document.' + lclObject + ".focus()") ;
     return false;
     }
return true;
}


As for the number of line breaks, try countin for Line Feed: chr(10) and Enter: chr(13) to see what's going on. I could write some sample code for that if it is not clear.

Fritz the Blank
ASKER CERTIFIED SOLUTION
Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of CodeHead
CodeHead

ASKER

mplungjan,
I need to specify that it can be either 4 lines with each line only allowed 70 characters.  If the line exceeds 70 characters I need to replace the information with a /n break in between the text closest to the 70th character then recount.  It also must be only 280 characters for the whole textarea field.  I have increased the points to 400.  The reason behind this is because we are writing information to a pdf that has a limited amount of lines and space for each line.  

This is what I tried but did not work
function checkTextArea(boxName, length) {
     var stringLen = boxName.value;
     var newText = "";
     var stripString = "";
     var x=0,y=0,z=0;
     var maxLines = 0;
     var lineCount = 0;
     
     //70 CHAR's = 1 line

     //set stripString = text box value
     stripString = boxName.value;
     
     //Get line returns allowed
     maxLines = parseInt(length/70);
     
     //Check line returns
     for (x = 0; x < stripString.length;x++) {
     
          z += 1;
               
          checkText = stripString.substring(x,x+2);
          if (checkText.indexOf("\n") > 0) {
               y=0;
               lineCount += 1;
               z=0;
          }
     
          if (z > 2) {
               if (y == 70) {
                    y=0;
                    lineCount += 1;
               }
          }
         
          y += 1;
     }

     if ((lineCount) == maxLines) {
          alert("You have exceeded the character limit or line limit for this field.\nIf you continue the information will be truncated on the document.\n\nPlease review the information and make any necessary changes.");
     }
     boxName.value = stripString.substring(0,length);
}

Thanks.
I got it.  The problem I had is that I was forgetting to go back to the first space character.  See
if this works for you.

<SCRIPT>

function checkTextArea() {

stringVal = document.myform.mytext.value

///////////////  First Row  ///////////////////
       

     /////// Grab the first 71 characters  ///////////////
           checkText = stringVal.substring(0,70);
       
 
    /////// Locate the last space before the 70th character  
        getlast = checkText.lastIndexOf(' ',70);
   
    //If the last space is the 71st character then we add
    // the hard return to the end of the 70th characters for the first row

    if(getlast == 70)
    {
       firstrow = stringVal.substring(0,69) + "\n";
 
       // Set the next character to 70 for the second row
       nextchar = 70;
    }
    else
    {
      // If not then take up to the last space
      firstrow = stringVal.substring(0,getlast) + "\n";

      // Set the next character one after the space
      nextchar = getlast + 1;
    }

 //Verify that there are more characters to continue

 if(stringVal.length > nextchar)
 {
  ///////////////  Second Row  ///////////////////
       
     /////// Grab the next 71 characters starting w/ 'nextchar' //////
 
          checkText2 = stringVal.substring(nextchar,nextchar+71);

    /////// Locate the last space before the 70th character  
        getlast2 = checkText2.lastIndexOf(' ',70);

    //If the last space is the 71st character then we add
    // the hard return to the end of the 70th characters for the first row

    if(getlast2 == 70)
    {
       secondrow = checkText2.substring(0,69) + "\n";
 
       // Set the next character to 70 for the second row
       nextchar += 70;
    }
    else
    {
      // If not then take up to the last space
      secondrow = checkText2.substring(0,getlast2) + "\n";

      // Set the next character one after the space
      nextchar += getlast2 + 1;
    }
 }

 //Verify that there are more characters to continue

 if(stringVal.length > nextchar)
 {
  ///////////////  Third Row  ///////////////////
       
     /////// Grab the next 71 characters starting w/ 'nextchar' //////
 
          checkText3 = stringVal.substring(nextchar,nextchar+71);

    /////// Locate the last space before the 70th character  
        getlast3 = checkText3.lastIndexOf(' ',70);

    //If the last space is the 71st character then we add
    // the hard return to the end of the 70th characters for the first row

    if(getlast3 == 70)
    {
       thirdrow = checkText3.substring(0,69) + "\n";
 
       // Set the next character to 70 for the second row
       nextchar += 70;
    }
    else
    {
      // If not then take up to the last space
      thirdrow = checkText3.substring(0,getlast3) + "\n";

      // Set the next character one after the space
      nextchar += getlast3 + 1;
    }
 }

 //Verify that there are more characters to continue

 if(stringVal.length > nextchar)
 {
   ///////////////  Forth Row  ///////////////////
       
     /////// Grab the rest of the string //////

      checkText4 = stringVal.substring(nextchar,stringVal.length);

     //// Make sure the balance of the string does not exceed 70 characters

      if(checkText4.length > 70)
        {
         
        alert("You have exceeded the character limit or line limit for this field.\nIf you continue
the information will be truncated on the document.\n\nPlease review the information and make any necessary
changes.");

         }
        else
        {
         // If 70 or less all is well
         
         fourthrow = checkText4;
        }
 }
alert(firstrow + secondrow + thirdrow + fourthrow);
}

</SCRIPT>

<form name=myform>

<TEXTAREA ROWS=4 COLS=70 NAME="mytext"></TEXTAREA>
<BR>
<INPUT TYPE=button VALUE="CHECK IT" onClick="checkTextArea()">
</form>
I am very busy. Here is what I did so far

<script>
function validate(theForm)  {
  msg ="";
  var count=0;
  var lines=new Array();
  var val = ""+theForm.myTextArea.value;
  if (val.indexOf('\n') !=-1) var lines = val.split('\n');
  else lines[0]=val;
  if (lines[lines.length-1].length==0) lines.length--;
  if (lines.length>4) msg += 'Please enter only 4 lines\nI have\n>'+lines.join('\n>');
  else {

     reformatNeeded = false;  
     for (i=0;i<lines.length;i++) {
        if (lines[i].length>70) {
          reformatNeeded = true;
          break;
        }
     }
     var newLines = new Array();
     count=0;
     var aLine='';
     if (reformatNeeded) {  
        wordsArray = lines.join(' ').split(' ');
        alert(wordsArray)
        for (i=0;i<wordsArray.length;i++) {
           if (aLine.length+1+wordsArray[i].length > 69) {
              newLines[count++]=aLine.substring(1);
              aLine='';
           }
           aLine+=" "+wordsArray[i];
        }
        if (aLine) newLines[count++]=aLine;
     }
     if (newLines.length>4) msg += 'Please enter max 277 chars - (4 lines of approx 70 chars + 3 returns)';
     else {
        alert('reformatting')
        val= newLines.join('\n')
        alert(val)
        theForm.myTextArea.value=val;
        return false;
     }
  }

  if (msg) {
     alert(msg);
     theForm.myTextArea.focus()
     return false;
  }
  return true;
}
</script>
 
</head>
<body>
<form onSubmit="return validate(this)">
<textarea rows=10 cols=100 name="myTextArea"></textarea>
<input type="Submit">
</form>

mplungjan,
This is putting all the javascript in the textbox.  Looks like you are on track to making this correct.  As I had said it needs to be dynamic so we can change the line count.  Looks like I can just change "4" to a variable.  Could you see why it is filling in the textarea with the javascript.  I also updated the points to 400.  I am not sure why it did not work before.

andriv,
This script needs to be dynamic.  Some of the textarea fields might have 5 or 6 lines.
I guess I can only give away 300 points.
I dont know how you want to dynamically set the values but I altered the script to allow easy altering of number of characters and rows:

<SCRIPT>

function checkTextArea() {

// Alter maximum number of rows
var maxrows = 4;

// Alter maximum characters, 0 if no limit
var maxchar = 250;

var linenumb = new Array();

var nextchar = 0;

stringVal = document.myform.mytext.value

// If max character limit, check
if(maxchar > 0)
{
  if(stringVal.length > maxchar)
  {
    alert("You have exceeded the maximum number of characters of " + maxchar);
  }
}


for(i=1;i <= maxrows;i++)
{
/// Check to make sure there are characters left ///

  if((stringVal.length > nextchar) && (i < maxrows))
  {
     
    /////// Grab the 71 characters starting w/ 'nextchar' //////

         checkText = stringVal.substring(nextchar,nextchar+70);

   /////// Locate the last space before the 70th character  
       getlast = checkText.lastIndexOf(' ',70);

   //If the last space is the 71st character then we add
   // the hard return to the end of the 70th characters for the first row

     if(getlast == 70)
     {
      linenumb[i] = checkText.substring(0,69) + "\n";

      // Set the next character to 70 for the second row
      nextchar += 70;
     }
     else
     {
     // If not then take up to the last space
     linenumb[i] = checkText.substring(0,getlast) + "\n";

     // Set the next character one after the space
     nextchar += getlast + 1;
     }
   }
   //set last row
   else if((stringVal.length > nextchar) && (i = maxrows))
   {

     /////// Grab the rest of the string //////

     checkText = stringVal.substring(nextchar,stringVal.length);

    //// Make sure the balance of the string does not exceed 70 characters

     if(checkText.length > 70)
       {
         
       alert("You have exceeded the character limit or line limit for this field.\nIf you continue the information will be truncated on the document.\n\nPlease review the information and make any necessary changes.");

       }
       else
       {
        // If 70 or less all is well
       
        linenumb[i] = checkText;
       }
    }
}
var alltext = ""
// Convert array into a variable

for(i=1;i<=maxrows;i++)
{
if(linenumb[i] != "");
{
alltext += linenumb[i];
}
}

alert(alltext);
}

</SCRIPT>

<form name=myform>

<TEXTAREA ROWS=4 COLS=70 NAME="mytext"></TEXTAREA>
<BR>
<INPUT TYPE=button VALUE="CHECK IT" onClick="checkTextArea()">
</form>
Not sure what you mean by "javascript in the textbox"


<script>
maxLines = 4;
maxChars = 70;
function validate(theForm)  {
 msg ="";
 var count=0;
 var lines=new Array();
 var val = ""+theForm.myTextArea.value;
 if (val.indexOf('\n') !=-1) var lines = val.split('\n');
 else lines[0]=val;
 if (lines[lines.length-1].length==0) lines.length--;
 if (lines.length>4) msg += 'Please enter only '+maxLines+' lines\nI have\n>'+lines.join('\n>');
 else {

    reformatNeeded = false;  
    for (i=0;i<lines.length;i++) {
       if (lines[i].length>=maxChars) {
         reformatNeeded = true;
         break;
       }
    }
    var newLines = new Array();
    count=0;
    var aLine='';
    if (reformatNeeded) {  
       wordsArray = lines.join(' ').split(' ');
       alert(wordsArray)
       for (i=0;i<wordsArray.length;i++) {
          if (aLine.length+1+wordsArray[i].length > maxChars-1) {
             newLines[count++]=aLine.substring(1);
             aLine='';
          }
          aLine+=" "+wordsArray[i];
       }
       if (aLine) newLines[count++]=aLine;
    }
    if (newLines.length>maxLines) msg += 'Please enter max '+(maxLines*maxChars-maxLines)+' chars - ('+maxLines+' lines of approx '+maxChars+' chars + 3 returns)';
    else {
       alert('reformatting')
       val= newLines.join('\n')
       alert(val)
       theForm.myTextArea.value=val;
       return false;
    }
 }

 if (msg) {
    alert(msg);
    theForm.myTextArea.focus()
    return false;
 }
 return true;
}
</script>
 
</head>
<body>
<form onSubmit="return validate(this)">
<textarea rows=10 cols=100 name="myTextArea"></textarea>
<input type="Submit">
</form>
Oops
chars + 3 returns)';

should be

chars + '+maxLines+' returns)';
You have 18 open questions today, all of which need your attention.  ADMINISTRATION WILL BE CONTACTING YOU SHORTLY.  Moderators Computer101, Netminder, Mindphaser or I will return to finalize these as soon as possible if after 7 days no response by the Asker.  EXPERTS-->  please post closing recommendations before that time.

Below are your open questions as of today.  Questions which have been inactive for 21 days or longer are considered to be abandoned and for those, your options are:
1. Accept a Comment As Answer (use the button next to the Expert's name).
2. Close the question if the information was not useful to you, but may help others. You must tell the participants why you wish to do this, and allow for Expert response.  This choice will include a refund to you, and will move this question to our PAQ (Previously Asked Question) database.  If you found information outside this question thread, please add it.
3. Ask Community Support to help split points between participating experts, or just comment here with details and we'll respond with the process.
4. Delete the question (if it has no potential value for others).
   --> Post comments for expert of your intention to delete and why
   --> YOU CANNOT DELETE A QUESTION with comments; special handling by a Moderator is required.

For special handling needs, please post a zero point question in the link below and include the URL (question QID/link) that it regards with details.
https://www.experts-exchange.com/jsp/qList.jsp?ta=commspt
 
Please click this link for Help Desk, Guidelines/Member Agreement and the Question/Answer process.  https://www.experts-exchange.com/jsp/cmtyHelpDesk.jsp

Click you Member Profile to view your question history and please keep them updated. If you are a KnowledgePro user, use the Power Search option to find them.  

Questions which are LOCKED with a Proposed Answer but do not help you, should be rejected with comments added.  When you grade the question less than an A, please comment as to why.  This helps all involved, as well as others who may access this item in the future.  PLEASE DO NOT AWARD POINTS TO ME.

To view your open questions, please click the following link(s) and keep them all current with updates.
https://www.experts-exchange.com/questions/Q.12036479.html
https://www.experts-exchange.com/questions/Q.20009996.html
https://www.experts-exchange.com/questions/Q.20010855.html
https://www.experts-exchange.com/questions/Q.20069067.html
https://www.experts-exchange.com/questions/Q.20081532.html
https://www.experts-exchange.com/questions/Q.20090911.html
https://www.experts-exchange.com/questions/Q.20101218.html
https://www.experts-exchange.com/questions/Q.20107838.html
https://www.experts-exchange.com/questions/Q.20108744.html
https://www.experts-exchange.com/questions/Q.20113500.html
https://www.experts-exchange.com/questions/Q.20115787.html
https://www.experts-exchange.com/questions/Q.11486298.html
https://www.experts-exchange.com/questions/Q.20133500.html
https://www.experts-exchange.com/questions/Q.20142611.html
https://www.experts-exchange.com/questions/Q.20143201.html
https://www.experts-exchange.com/questions/Q.20145267.html
https://www.experts-exchange.com/questions/Q.20245016.html
https://www.experts-exchange.com/questions/Q.20296474.html



*****  E X P E R T S    P L E A S E  ******  Leave your closing recommendations.
If you are interested in the cleanup effort, please click this link
https://www.experts-exchange.com/jsp/qManageQuestion.jsp?ta=commspt&qid=20274643 
------> POINTS FOR EXPERTS awaiting comments are listed in the links below
https://www.experts-exchange.com/commspt/Q.20277028.html (Part 1)
https://www.experts-exchange.com/jsp/qShow.jsp?ta=commspt&qid=20295853 (Part 2)
 
Moderators will finalize this question if in @7 days Asker has not responded.  This will be moved to the PAQ (Previously Asked Questions) at zero points, deleted or awarded.
 
Thanks everyone.
Moondancer
Moderator @ Experts Exchange
Michel on this one I think.

Fritz the Blank
Thank you, finalized today.
Moondancer - EE Moderator