0

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
}
2
  • 2
    Of course. Please show us what you've tried.
    – user2625787
    Sep 15, 2013 at 23:58
  • You should do this on the backend, and just visually wrap the text on the front end (which I think is default anyway).
    – Petah
    Sep 16, 2013 at 0:10

3 Answers 3

0

Try this out. Demo: http://jsfiddle.net/ZtPPk/2

$("textarea").keyup(function(e) {
    var $this = $(this);
    var length = $this.val().length;
    if(length % 50 == 0) {
        $this.val($this.val() + "\n");   
    }
});
1
  • This works too, but just not on the first line. Thanks for your help.
    – Nubby
    Sep 16, 2013 at 0:25
0

Try

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

http://jsfiddle.net/2QZbG/

1
  • Thanks so much. Worked great.
    – Nubby
    Sep 16, 2013 at 0:24
0

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);
}
2
  • Thanks for that suggestion. But how can I get that to work for each line?
    – Nubby
    Sep 16, 2013 at 0:16
  • @Nubby, Updated my answer. You have use % to see if the length and multiple of 50 and add \n at the end.
    – Starx
    Sep 16, 2013 at 0:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.