0

I need to have a textarea that allows the user to enter only 2 lines of text.

I accomplished this by e.preventDefault() on a keyDown event when lineCount equals 2. The problem is when the user uses backspace, and deletes entered text.

How do I keep track of lines and allow typing again until the user enters two lines again?

Here is what I was able to accomplish:

var lineCount = 0;
$('#editor').keydown(function (e) {
    if (e.keyCode == 13) {
        lineCount++;
    }
    if (e.keyCode == 8) {
       //needs to remove characters, deduct linecount when it gets to first line and reinstate typing
       return true;
    }
    if (lineCount >= 2) {
       e.preventDefault();
       return false;
    }
});

http://jsfiddle.net/blueberry20/yphkafqn/2/

Dan Beaulieu
  • 19,406
  • 19
  • 101
  • 135
sloth_eyes
  • 127
  • 1
  • 10

1 Answers1

0

Maybe something like this in jQuery (>1.6):

$(document).ready(function () {

    var lines = 2;

    $('#mytext').keydown(function (e) {
        newLines = $(this).val().split("\n").length;

        if (newLines > lines) {
            $("#mytext").prop('disabled', true);
        } else {
            $("#mytext").prop('disabled', false);
        }
    });

    $('#button').click(function () {
        $("#mytext").val('');
        $("#mytext").prop('disabled', false);
    });
});

http://jsfiddle.net/6vwLLu5h/1/

It doesn't work for pastes and if the user doesn't use line breaks.

hatef
  • 5,491
  • 30
  • 43
  • 46
  • From a usability standpoint, that is terrible. If the user tries to enter a third line, everything is locked in place and no further editing can be done. Why would *anyone* want that? – riwalk May 15 '15 at 22:29
  • @Stargazer712 true - I gave one possible solution regarding his question - digging more he can add more features to it: one button to re-enable the *textarea*? - in real world someone may want that though. :) – hatef May 15 '15 at 22:37