-2

I've got a form that people can fill out and the results of the form are displayed on a page. The form is limited to 2000 characters, however there's nothing limiting how many line breaks there can be, so someone could just put one character per line and get 2000 line breaks, which clutters up the page pretty badly. I'm looking to limit the number of lines that they can type into the textarea so the limits are 2000 characters or 40 lines, whichever comes first.

I would also need this to be protective of people pasting large amounts of text into the form as well. I looked at a lot of other posts about this but none of the answers worked when I tried them. Thanks!

Treedot
  • 101
  • 1
  • 10

1 Answers1

1

have you specified <textarea maxlength="2000"></textarea> - that would be a good place to start. this would limit the characters to 2000.

You could also check for the enter key (keycode=="13" if i recollect correctly) and either a) disallow it or b) only allow it after a full stop or after e.g. >30 characters. Just a suggestion

Definitely specify the maxlength though. Then no more than that will be able to be inputted. Note that breaks count as characters and are deducted from the characters remaining.

Have a go at this and you will see.

function textCount(val) {
    var len = val.value.length;

    if (len >= 500) {
        val.value = val.value.substring(0, 2000);
        $('#amtleft span').text(0);
    } else {
        $('#amtleft span').text(2000 - len);
    }
}
textCount($('#longText').get(0));
$('#longText').keyup(function() {
    textCount(this);
});
textarea{height:150px;
width:300px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<textarea id='longText' ></textarea><br>
<span id='amtleft'><label>&#40;<span>2000</span> characters left&#41;</label></span>
Rachel Gallen
  • 27,943
  • 21
  • 72
  • 81