Limiting number of lines and letters in single line in textarea

前端 未结 4 1585
感情败类
感情败类 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:21

    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.

提交回复
热议问题