Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Wrap lines after x number of characters in textarea

Status
Not open for further replies.

aeboi80

Programmer
Jul 13, 2010
1
US
Hey guys,

A little bit of explanation:

I have a textarea with a specific width. I have wrap="off" set because I don't want to force my users to wrap if they don't want to. The reason for this is because this textarea is where the user is typing an email message. However I have a background image set on the textarea with a verticle line going down the textarea which indicates to the user the "Recommend Width"

What I want to do is provide them with a link to click on which says something like "Wrap Lines" and when they click on it, the text within the textarea would wrap to the "Recommended Width" line in the background image. The maximum length of a line should be 53 characters when they click on "Wrap Lines" link.

So I did some searching around and the code I came up with is:

Code:
function showLines(max, text) {
max--;
text = "" + text;
var temp = "";
var chcount = 0; 
for (var i = 0; i < text.length; i++) // for each character ... 
{   
var ch = text.substring(i, i+1); // first character
var ch2 = text.substring(i+1, i+2); // next character
if (ch == '\n') // if character is a hard return
{  
temp += ch;
chcount = 1;
}
else
{
if (chcount == max) // line has max chacters on this line
{
temp += '\n' + ch; // go to next line
chcount = 1; // reset chcount
}
else  // Not a newline or max characters ...
{
temp += ch;
chcount++; // so add 1 to chcount
      }
   }
}
return (temp); // sends value of temp back
}

Which is activated by using a HTML submit form button

Code:
<input type=button value="Wrap Lines to 53 Spaces"
onClick="this.form.text1.value = showLines(53, this.form.text1.value)">

The problem with this code is that when it gets to the 53 character on the line it does the word wrap, even if its in the middle of the word.

So a sentence like:

This sentence is going to wrap in the middle of a wor
d

Can anyone help me in figuring out how to prevent this from happening and wrap the entire word instead of just doing it in the middle of a word?

Thanks :)

Chad
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top