0

I have a text area that can take 10000 characters. i want to put the line breaker on each line of the text area value after 10 character

something like this i want to achive

11111111 1
111 111 11
11 11 11 1

all above line has 10 characters each.

var start = 3
var times = 1;
$('.mydesc').keyup(function () {
    var len = $(this).val().length;
    if (len == start) {
        this.value += '\n';
        times = ++times;
        start= ((start * 2) + start);
    }
});

but doesn't work ..

nicolallias
  • 1,055
  • 2
  • 22
  • 51
monda
  • 3,809
  • 15
  • 60
  • 84
  • 1
    Actually I did not get the line "start= ((start * 2) + start);" , why not just "start * 3" ? – Y.Puzyrenko Apr 04 '14 at 13:11
  • Do you want to store the line breaks, or just have them shown in the textarea for formatting purposes? – Smeegs Apr 04 '14 at 13:14
  • possible duplicate of [How can I insert a character after every n characters in javascript?](http://stackoverflow.com/questions/1772941/how-can-i-insert-a-character-after-every-n-characters-in-javascript) – Pete Apr 04 '14 at 13:14

3 Answers3

7

Simplest solution is to always re-add all of the new-lines:

$('.mydesc').keyup(function () {
    this.value = this.value
                     .replace(/[\n\r]+/g, "")
                     .replace(/(.{10})/g, "$1\n");
});

http://jsfiddle.net/s4cUz/

pozs
  • 34,608
  • 5
  • 57
  • 63
1

Something like this would do it:

http://jsfiddle.net/Zxuj7/

$('#test_textarea').keyup(function () {
   var new_stuff = $(this).val();
       new_stuff = new_stuff.replace(/[\n\r]+/g,""); // clean out newlines, so we dont get dups!
   var test = new_stuff.replace(/(.{10})/g,"$1\n");
   $(this).val(test);
});

However, be aware that it doesn't work that well with the "deleting" of characters. If you give it a go, you will notice that when you actually delete a character and the code runs, it will put you at the end of the textarea again (because its "overwriting" the value)

UPDATE:

You may actually be better formatting AFTER they have finished editing the textarea - i.e using blur();

$('#test_textarea').blur(function () {
    // leaving the field... so lets try and format nicely now
    var new_stuff = $(this).val();
           new_stuff = new_stuff.replace(/[\n\r]+/g,""); // clean out newlines, so we dont get dups!
           new_stuff = new_stuff.replace(/(.{10})/g,"$1\n");
    $(this).val(new_stuff);
});

Although that doesn't do it in real time - it does work better when deleting/editing the contents

Andrew Newby
  • 4,941
  • 6
  • 40
  • 81
1

Enhanced version of Andrew Newby's script:

$('#test_textarea').keyup(function (e) {
     if (e.keyCode === 8) return; // Backspace
     var new_stuff = $(this).val();
     new_stuff = new_stuff.replace(/[\n\r]+/g,""); // clean out newlines, so we dont get dups!
     new_stuff = new_stuff.replace(/(.{10})/g,"$1\n");
     $(this).val(new_stuff);
});

This actually ignores backspace key, so at least that interaction is preserved.