Limiting number of lines and letters in single line in textarea

前端 未结 4 1588
感情败类
感情败类 2020-12-18 08:39

Problem:
I am trying to limit number of lines AND letters in each line in a textbox.

What i got so far:
So far i managed t

4条回答
  •  死守一世寂寞
    2020-12-18 09:26

    Here's what I came up with. Fairly clean and seems to work for all the tests I can give it.

    JavaScript:

    $(function () {
        $('textarea').on('keypress', function (event) {
            var text = $('textarea').val();
            var lines = text.split("\n");
            var currentLine = this.value.substr(0, this.selectionStart).split("\n").length;
            console.log(lines);
            console.log(currentLine);
            console.log(lines[currentLine - 1]);
            if (event.keyCode == 13) {
                if (lines.length >= $(this).attr('rows')) return false;
            } else {
                if (lines[currentLine - 1].length >= $(this).attr('cols')) {
                    return false; // prevent characters from appearing
                }
            }
        });
    });
    

    HTML:

    
    

    DEMO

提交回复
热议问题