Word wrap a textarea at x number of characters

Word wrap a textarea at x number of characters

Hello,

I am currently seeking help on how to best approach finding a solution to this.

Essentially I have a textarea which a user is supposed to be typing a text based email message(no HTML)  The textarea has a column width of 80

However there is a recommended width of 53 characters per line.  Obviously the user can just keep on typing away past the 53 character recommended width if they want, but I want to add either a form button or a link with an onClick that analyzes the contents of the textarea.  It should insert a hard return when it reaches 53 characters, but if the 53rd character is in the middle of a word it should count back to the previous space and do the line wrap there.

Can anyone point me in the right direction?  I assumed there has to a solution using jQuery, but I am at a loss.  I did come across some javascript which works, but it doesn't take into account the fact that the 53rd character maybe in the middle of a word.

  1. <head>
  2. <title>Textarea Test</title>
  3. <script type="text/javascript">

  4. <!-- Begin
  5. function showLines(max, text) {
  6. max--;
  7. text = "" + text;
  8. var temp = "";
  9. temp = temp.replace(/^(.{53}\w+)/mg,"$1\n");
  10. var chcount = 0; 
  11. for (var i = 0; i < text.length; i++) // for each character ... 
  12. {
  13. var ch = text.substring(i, i+1); // first character
  14. var ch2 = text.substring(i+1, i+2); // next character
  15. if (ch == '\n') // if character is a hard return
  16. {
  17. temp += ch;
  18. chcount = 1;
  19. }
  20. else
  21. {
  22. if (chcount == max) // line has max chacters on this line
  23. {
  24. temp += '\n' + ch; // go to next line
  25. chcount = 1; // reset chcount
  26. }
  27. else  // Not a newline or max characters ...
  28. {
  29. temp += ch;
  30. chcount++; // so add 1 to chcount
  31. }
  32. }
  33. }
  34. return (temp); // sends value of temp back
  35. }
  36. //  End -->
  37. </script>
  38. </head>

  39. <body>

  40. <p align="center">
  41. <form name=form1>
  42. <textarea name=text1 rows=15 cols=80>This is just an example of a long textbox entry that just went on and on and on and on.....  The visitor did not hit <enter> when entering this information so it continued off the right side of the textarea box.  Notice that hitting <enter> after each line, like this:
  43. This is on another line
  44. And so is this one.....

  45. Still wraps correctly.  Neat!</textarea><br>
  46. <input type=button value="Wrap Lines to 53 Spaces"
  47. onClick="this.form.text1.value = showLines(53, this.form.text1.value)">


  48. </form>
  49. </p>

  50. </body>
  51. </html>
Thanks for any assistance you can provide.

Chad