September 16, 2013

How can I automatically add line breaks in a textarea?

Nubby’s Question:

I have a textarea that isn’t very wide. I want as the user enters text for there to be line break once a line has 50 characters. I don’t want any wrapped text. Just line breaks. Is there a way to make this happen?

I tried to test something basic out on one line and failed.

$('#textarea').keypress(function (e) {
if ($(this).val().length == 50) {
    $(this).val()[51] == 'n'

I clearly am not very experienced. I don’t know if I should start looking into the regExp object.

I can’t allow wrapped text because I need to measure what each line of the textarea has. After the user has submitted the form, I need to be able to use something like this:

var line = $('#textarea').val().split('n');
for(i = 0; i < line.length; i++){
    // do something


$('textarea').keypress(function () {
  var length = $(this).val().length;
  if (length % 51 == 0 &&
      length > 0) {
    var val = $(this).val();
    $(this).val(val + 'n');

You have use % to see if the length and multiple of 50 and add n at the end. Demo

if ($(this).val().length % 50 == 0) {
    $(this).val($(this).val() + 'n);

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+


Please fill the form - I will response as fast as I can!