Limiting number of lines and letters in single line in textarea

橙三吉。 提交于 2019-11-29 07:57:26

Tested in chrome : http://jsfiddle.net/3e3EH/1/

$(document).ready(function(){
    var textArea = $('#foo');
    var maxRows = textArea.attr('rows');
    var maxChars = textArea.attr('cols');
    textArea.keypress(function(e){
        var text = textArea.val();
        var lines = text.split('\n');
        if (e.keyCode == 13){
            return lines.length < maxRows;
        }
        else{
            var caret = textArea.get(0).selectionStart;
            console.log(caret);

            var line = 0;
            var charCount = 0;
            $.each(lines, function(i,e){
                charCount += e.length;
                if (caret <= charCount){
                    line = i;
                    return false;
                }
                //\n count for 1 char;
                charCount += 1;
            });

            var theLine = lines[line];
            return theLine.length < maxChars;
        }
    });

});​

Edit

As jbabey pointed out, ctrl+v or right-click -> paste can be an issue. right click can easily be prevented. for ctrl+v, you probable can detect it too... Just disabling javascript will obviously break the thing, too. Anyways, as any client-side validation, you have to double check on server-side.

jeschafe

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:

<textarea rows="10" cols="15"></textarea>

DEMO

brian buck

Instead of looping over each line get the current line number of your cursor and check only the character length of that line. See this SO answer for implementation details.

Then change your else statement to look like this:

else{
    var currLine = getLineNumber();
    if (lines[currLine].length >= $(this.attr('cols')) {
        return false; // prevent characters from appearing
    }
}

A little late, but i made this plugin https://github.com/luisdalmolin/jquery-limitLines.

Can be usefull sometimes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!