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
}
Try
$('textarea').keypress(function () {
var length = $(this).val().length;
if (length % 51 == 0 &&
length > 0) {
var val = $(this).val();
$(this).val(val + 'n');
}
});