简体   繁体   中英

Put line break after 10 characters in text area

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 ..

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/

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 - ie 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM